@defisaver/positions-sdk 0.0.21 → 0.0.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -63
- package/cjs/aaveV2/index.js +1 -3
- package/cjs/aaveV3/index.js +12 -14
- package/cjs/morphoAaveV3/index.js +1 -3
- package/cjs/spark/index.js +1 -3
- package/esm/aaveV2/index.js +2 -4
- package/esm/aaveV3/index.js +2 -4
- package/esm/morphoAaveV3/index.js +1 -3
- package/esm/spark/index.js +2 -4
- package/package.json +40 -40
- package/src/aaveV2/index.ts +226 -231
- package/src/aaveV3/index.ts +561 -565
- package/src/assets/index.ts +60 -60
- package/src/chickenBonds/index.ts +123 -123
- package/src/compoundV2/index.ts +219 -219
- package/src/compoundV3/index.ts +275 -275
- package/src/config/contracts.js +673 -673
- package/src/constants/index.ts +3 -3
- package/src/contracts.ts +100 -100
- package/src/curveUsd/index.ts +228 -228
- package/src/exchange/index.ts +17 -17
- package/src/helpers/aaveHelpers/index.ts +134 -134
- package/src/helpers/chickenBondsHelpers/index.ts +23 -23
- package/src/helpers/compoundHelpers/index.ts +181 -181
- package/src/helpers/curveUsdHelpers/index.ts +32 -32
- package/src/helpers/index.ts +5 -5
- package/src/helpers/makerHelpers/index.ts +94 -94
- package/src/helpers/sparkHelpers/index.ts +106 -106
- package/src/index.ts +40 -40
- package/src/liquity/index.ts +116 -116
- package/src/maker/index.ts +101 -101
- package/src/markets/aave/index.ts +80 -80
- package/src/markets/aave/marketAssets.ts +32 -32
- package/src/markets/compound/index.ts +141 -141
- package/src/markets/compound/marketsAssets.ts +46 -46
- package/src/markets/curveUsd/index.ts +69 -69
- package/src/markets/index.ts +3 -3
- package/src/markets/spark/index.ts +29 -29
- package/src/markets/spark/marketAssets.ts +9 -9
- package/src/moneymarket/moneymarketCommonService.ts +75 -75
- package/src/morpho/markets.ts +39 -39
- package/src/morphoAaveV2/index.ts +255 -255
- package/src/morphoAaveV3/index.ts +619 -624
- package/src/multicall/index.ts +22 -22
- package/src/services/dsrService.ts +15 -15
- package/src/services/priceService.ts +21 -21
- package/src/services/utils.ts +34 -34
- package/src/spark/index.ts +421 -425
- package/src/staking/staking.ts +167 -167
- package/src/types/aave.ts +256 -256
- package/src/types/chickenBonds.ts +45 -45
- package/src/types/common.ts +83 -83
- package/src/types/compound.ts +128 -128
- package/src/types/curveUsd.ts +112 -112
- package/src/types/index.ts +6 -6
- package/src/types/liquity.ts +30 -30
- package/src/types/maker.ts +50 -50
- package/src/types/spark.ts +106 -106
package/src/aaveV3/index.ts
CHANGED
|
@@ -1,565 +1,561 @@
|
|
|
1
|
-
import Web3 from 'web3';
|
|
2
|
-
import Dec from 'decimal.js';
|
|
3
|
-
import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
getConfigContractAbi,
|
|
9
|
-
getConfigContractAddress,
|
|
10
|
-
GhoTokenContract,
|
|
11
|
-
} from '../contracts';
|
|
12
|
-
import {
|
|
13
|
-
addToObjectIf, ethToWeth, getAbiItem, isLayer2Network, wethToEth, wethToEthByAddress,
|
|
14
|
-
} from '../services/utils';
|
|
15
|
-
import {
|
|
16
|
-
AaveMarketInfo,
|
|
17
|
-
AaveV3AssetData,
|
|
18
|
-
AaveV3AssetsData,
|
|
19
|
-
AaveV3IncentiveData,
|
|
20
|
-
AaveV3MarketData,
|
|
21
|
-
AaveV3PositionData,
|
|
22
|
-
AaveV3UsedAsset,
|
|
23
|
-
AaveV3UsedAssets,
|
|
24
|
-
EModeCategoryDataMapping,
|
|
25
|
-
} from '../types/aave';
|
|
26
|
-
import {
|
|
27
|
-
Blockish, EthAddress, NetworkNumber, PositionBalances,
|
|
28
|
-
} from '../types/common';
|
|
29
|
-
import { calculateNetApy, getStakingApy } from '../staking';
|
|
30
|
-
import { multicall } from '../multicall';
|
|
31
|
-
import { IUiIncentiveDataProviderV3 } from '../types/contracts/generated/AaveUiIncentiveDataProviderV3';
|
|
32
|
-
import { getAssetsBalances } from '../assets';
|
|
33
|
-
import { calculateBorrowingAssetLimit } from '../moneymarket';
|
|
34
|
-
import {
|
|
35
|
-
aaveAnyGetAggregatedPositionData,
|
|
36
|
-
aaveV3IsInIsolationMode,
|
|
37
|
-
aaveV3IsInSiloedMode,
|
|
38
|
-
} from '../helpers/aaveHelpers';
|
|
39
|
-
import { AAVE_V3 } from '../markets/aave';
|
|
40
|
-
|
|
41
|
-
export const test = (web3: Web3, network: NetworkNumber) => {
|
|
42
|
-
const contract = AaveV3ViewContract(web3, 1);
|
|
43
|
-
return contract.methods.AAVE_REFERRAL_CODE().call();
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
export const aaveV3CalculateDiscountRate = (
|
|
47
|
-
debtBalance: string,
|
|
48
|
-
discountTokenBalance: string,
|
|
49
|
-
discountRate: string,
|
|
50
|
-
minDiscountTokenBalance: string,
|
|
51
|
-
minGhoBalanceForDiscount: string,
|
|
52
|
-
ghoDiscountedPerDiscountToken: string,
|
|
53
|
-
) => {
|
|
54
|
-
if (new Dec(discountTokenBalance).lt(minDiscountTokenBalance) || new Dec(debtBalance).lt(minGhoBalanceForDiscount)) {
|
|
55
|
-
return '0';
|
|
56
|
-
}
|
|
57
|
-
const discountedBalance = new Dec( // wadMul
|
|
58
|
-
new Dec(discountTokenBalance).mul(ghoDiscountedPerDiscountToken).add(new Dec(1e18).div(2)),
|
|
59
|
-
).div(1e18).toDP(0);
|
|
60
|
-
|
|
61
|
-
if (new Dec(discountedBalance).gte(debtBalance)) {
|
|
62
|
-
return new Dec(discountRate).div(10000).toDP(4).toString();
|
|
63
|
-
}
|
|
64
|
-
return new Dec(discountedBalance)
|
|
65
|
-
.mul(discountRate)
|
|
66
|
-
.div(debtBalance)
|
|
67
|
-
.div(10000)
|
|
68
|
-
.toDP(4)
|
|
69
|
-
.toString();
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
export const aaveV3EmodeCategoriesMapping = (extractedState: any, usedAssets: AaveV3UsedAssets) => {
|
|
73
|
-
const { assetsData }: { assetsData: AaveV3AssetsData } = extractedState;
|
|
74
|
-
const usedAssetsValues = Object.values(usedAssets);
|
|
75
|
-
|
|
76
|
-
const categoriesMapping: { [key: number]: EModeCategoryDataMapping } = {};
|
|
77
|
-
Object.values(assetsData).forEach((a: AaveV3AssetData) => {
|
|
78
|
-
const borrowingOnlyFromCategory = a.eModeCategory === 0
|
|
79
|
-
? true
|
|
80
|
-
: !usedAssetsValues.filter(u => u.isBorrowed && u.eModeCategory !== a.eModeCategory).length;
|
|
81
|
-
const afterEnteringCategory = aaveAnyGetAggregatedPositionData({
|
|
82
|
-
...extractedState, usedAssets, eModeCategory: a.eModeCategory,
|
|
83
|
-
});
|
|
84
|
-
const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent);
|
|
85
|
-
const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized];
|
|
86
|
-
|
|
87
|
-
categoriesMapping[a.eModeCategory] = {
|
|
88
|
-
enteringTerms,
|
|
89
|
-
canEnterCategory: !enteringTerms.includes(false),
|
|
90
|
-
id: a.eModeCategory,
|
|
91
|
-
data: a.eModeCategoryData,
|
|
92
|
-
assets: a.eModeCategory === 0 ? [] : [...(categoriesMapping[a.eModeCategory]?.assets || []), a.symbol],
|
|
93
|
-
enabledData: {
|
|
94
|
-
ratio: afterEnteringCategory.ratio,
|
|
95
|
-
liqRatio: afterEnteringCategory.liqRatio,
|
|
96
|
-
liqPercent: afterEnteringCategory.liqPercent,
|
|
97
|
-
collRatio: afterEnteringCategory.collRatio,
|
|
98
|
-
},
|
|
99
|
-
};
|
|
100
|
-
});
|
|
101
|
-
return categoriesMapping;
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
export async function getAaveV3MarketData(web3: Web3, network: NetworkNumber, market: AaveMarketInfo, defaultWeb3: Web3): Promise<AaveV3MarketData> {
|
|
105
|
-
const _addresses = market.assets.map(a => getAssetInfo(ethToWeth(a), network).address);
|
|
106
|
-
|
|
107
|
-
const isL2 = isLayer2Network(network);
|
|
108
|
-
|
|
109
|
-
const loanInfoContract = AaveV3ViewContract(web3, network);
|
|
110
|
-
const aaveIncentivesContract = AaveIncentiveDataProviderV3Contract(web3, network);
|
|
111
|
-
const marketAddress = market.providerAddress;
|
|
112
|
-
|
|
113
|
-
const GhoDiscountRateStrategyAddress = getConfigContractAddress('GhoDiscountRateStrategy', NetworkNumber.Eth);
|
|
114
|
-
const GhoDiscountRateStrategyAbi = getConfigContractAbi('GhoDiscountRateStrategy');
|
|
115
|
-
const GhoTokenAbi = getConfigContractAbi('GHO');
|
|
116
|
-
|
|
117
|
-
const multicallCallsObject = [
|
|
118
|
-
{
|
|
119
|
-
target: GhoDiscountRateStrategyAddress,
|
|
120
|
-
abiItem: getAbiItem(GhoDiscountRateStrategyAbi, 'GHO_DISCOUNTED_PER_DISCOUNT_TOKEN'),
|
|
121
|
-
params: [],
|
|
122
|
-
},
|
|
123
|
-
{
|
|
124
|
-
target: GhoDiscountRateStrategyAddress,
|
|
125
|
-
abiItem: getAbiItem(GhoDiscountRateStrategyAbi, 'DISCOUNT_RATE'),
|
|
126
|
-
params: [],
|
|
127
|
-
},
|
|
128
|
-
{
|
|
129
|
-
target: GhoDiscountRateStrategyAddress,
|
|
130
|
-
abiItem: getAbiItem(GhoDiscountRateStrategyAbi, 'MIN_DISCOUNT_TOKEN_BALANCE'),
|
|
131
|
-
params: [],
|
|
132
|
-
},
|
|
133
|
-
{
|
|
134
|
-
target: GhoDiscountRateStrategyAddress,
|
|
135
|
-
abiItem: getAbiItem(GhoDiscountRateStrategyAbi, 'MIN_DEBT_TOKEN_BALANCE'),
|
|
136
|
-
params: [],
|
|
137
|
-
},
|
|
138
|
-
{
|
|
139
|
-
target: getAssetInfo('GHO').address,
|
|
140
|
-
abiItem: getAbiItem(GhoTokenAbi, 'getFacilitatorsList'),
|
|
141
|
-
params: [],
|
|
142
|
-
},
|
|
143
|
-
];
|
|
144
|
-
|
|
145
|
-
const ghoContract = GhoTokenContract(web3, network);
|
|
146
|
-
|
|
147
|
-
// eslint-disable-next-line prefer-const
|
|
148
|
-
let [loanInfo, isBorrowAllowed, multiRes] = await Promise.all([
|
|
149
|
-
loanInfoContract.methods.getFullTokensInfo(marketAddress, _addresses).call(),
|
|
150
|
-
loanInfoContract.methods.isBorrowAllowed(marketAddress).call(), // Used on L2s check for PriceOracleSentinel (mainnet will always return true)
|
|
151
|
-
isL2 ? [{ 0: null }, { 0: null }, { 0: null }, { 0: null }, { 0: null }] : multicall(multicallCallsObject, web3, network),
|
|
152
|
-
]);
|
|
153
|
-
isBorrowAllowed = isLayer2Network(network) ? isBorrowAllowed : true;
|
|
154
|
-
|
|
155
|
-
const [
|
|
156
|
-
{ 0: ghoDiscountedPerDiscountToken },
|
|
157
|
-
{ 0: discountRate },
|
|
158
|
-
{ 0: minDiscountTokenBalance },
|
|
159
|
-
{ 0: minGhoBalanceForDiscount },
|
|
160
|
-
{ 0: facilitatorsList },
|
|
161
|
-
] = multiRes;
|
|
162
|
-
|
|
163
|
-
let rewardInfo: IUiIncentiveDataProviderV3.AggregatedReserveIncentiveDataStructOutput[] | null = null;
|
|
164
|
-
if (network === 10) {
|
|
165
|
-
rewardInfo = await aaveIncentivesContract.methods.getReservesIncentivesData(marketAddress).call();
|
|
166
|
-
rewardInfo = rewardInfo.reduce((all: any, _market: AaveV3IncentiveData) => {
|
|
167
|
-
// eslint-disable-next-line no-param-reassign
|
|
168
|
-
all[_market.underlyingAsset] = _market;
|
|
169
|
-
return all;
|
|
170
|
-
}, {});
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const assetsData: AaveV3AssetData[] = await Promise.all(loanInfo
|
|
174
|
-
.map(async (tokenMarket, i) => {
|
|
175
|
-
const symbol = market.assets[i];
|
|
176
|
-
const nativeAsset = symbol === 'GHO';
|
|
177
|
-
|
|
178
|
-
let borrowCap = tokenMarket.borrowCap;
|
|
179
|
-
let discountRateOnBorrow = '0';
|
|
180
|
-
|
|
181
|
-
if (nativeAsset && facilitatorsList && discountRate && minDiscountTokenBalance && minGhoBalanceForDiscount && ghoDiscountedPerDiscountToken) {
|
|
182
|
-
const facilitatorBucket = await ghoContract.methods.getFacilitatorBucket(facilitatorsList[0]).call();
|
|
183
|
-
const availableFacilitatorCap = assetAmountInEth(new Dec(facilitatorBucket[0]).sub(facilitatorBucket[1]).toString(), 'GHO');
|
|
184
|
-
|
|
185
|
-
borrowCap = Dec.min(borrowCap, availableFacilitatorCap).toString();
|
|
186
|
-
|
|
187
|
-
discountRateOnBorrow = aaveV3CalculateDiscountRate(
|
|
188
|
-
tokenMarket.totalBorrow.toString(),
|
|
189
|
-
'3160881469228662060510133', // stkAAVE total supply
|
|
190
|
-
discountRate,
|
|
191
|
-
minDiscountTokenBalance,
|
|
192
|
-
minGhoBalanceForDiscount,
|
|
193
|
-
ghoDiscountedPerDiscountToken,
|
|
194
|
-
);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
let marketLiquidity = nativeAsset
|
|
198
|
-
? assetAmountInEth(new Dec(assetAmountInWei(borrowCap.toString(), 'GHO'))
|
|
199
|
-
.sub(tokenMarket.totalBorrow.toString())
|
|
200
|
-
.toString(), symbol)
|
|
201
|
-
: assetAmountInEth(new Dec(tokenMarket.totalSupply.toString())
|
|
202
|
-
.sub(tokenMarket.totalBorrow.toString())
|
|
203
|
-
.toString(), symbol);
|
|
204
|
-
|
|
205
|
-
if (new Dec(marketLiquidity).lt(0)) {
|
|
206
|
-
marketLiquidity = '0';
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return ({
|
|
210
|
-
nativeAsset,
|
|
211
|
-
...addToObjectIf(nativeAsset, {
|
|
212
|
-
discountData: {
|
|
213
|
-
ghoDiscountedPerDiscountToken,
|
|
214
|
-
discountRate,
|
|
215
|
-
minDiscountTokenBalance,
|
|
216
|
-
minGhoBalanceForDiscount,
|
|
217
|
-
},
|
|
218
|
-
}),
|
|
219
|
-
symbol,
|
|
220
|
-
isIsolated: new Dec(tokenMarket.debtCeilingForIsolationMode).gt(0),
|
|
221
|
-
debtCeilingForIsolationMode: new Dec(tokenMarket.debtCeilingForIsolationMode).div(100).toString(),
|
|
222
|
-
isSiloed: tokenMarket.isSiloedForBorrowing,
|
|
223
|
-
eModeCategory: +tokenMarket.emodeCategory,
|
|
224
|
-
isolationModeTotalDebt: new Dec(tokenMarket.isolationModeTotalDebt).div(100).toString(),
|
|
225
|
-
assetId: Number(tokenMarket.assetId),
|
|
226
|
-
underlyingTokenAddress: tokenMarket.underlyingTokenAddress,
|
|
227
|
-
supplyRate: new Dec(tokenMarket.supplyRate.toString()).div(1e25).toString(),
|
|
228
|
-
borrowRate: new Dec(tokenMarket.borrowRateVariable.toString()).div(1e25).toString(),
|
|
229
|
-
borrowRateDiscounted: nativeAsset ? new Dec(tokenMarket.borrowRateVariable.toString()).div(1e25).mul(1 - parseFloat(discountRateOnBorrow)).toString() : '0',
|
|
230
|
-
borrowRateStable: new Dec(tokenMarket.borrowRateStable.toString()).div(1e25).toString(),
|
|
231
|
-
collateralFactor: new Dec(tokenMarket.collateralFactor.toString()).div(10000).toString(),
|
|
232
|
-
liquidationRatio: new Dec(tokenMarket.liquidationRatio.toString()).div(10000).toString(),
|
|
233
|
-
marketLiquidity,
|
|
234
|
-
utilization: new Dec(tokenMarket.totalBorrow.toString())
|
|
235
|
-
.div(new Dec(tokenMarket.totalSupply.toString()))
|
|
236
|
-
.times(100)
|
|
237
|
-
.toString(),
|
|
238
|
-
usageAsCollateralEnabled: tokenMarket.usageAsCollateralEnabled,
|
|
239
|
-
supplyCap: tokenMarket.supplyCap,
|
|
240
|
-
borrowCap,
|
|
241
|
-
totalSupply: assetAmountInEth(tokenMarket.totalSupply.toString(), symbol),
|
|
242
|
-
isInactive: !tokenMarket.isActive,
|
|
243
|
-
isFrozen: tokenMarket.isFrozen,
|
|
244
|
-
isPaused: tokenMarket.isPaused,
|
|
245
|
-
canBeBorrowed: tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen && tokenMarket.borrowingEnabled && isBorrowAllowed,
|
|
246
|
-
canBeSupplied: !nativeAsset && tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen,
|
|
247
|
-
canBeWithdrawn: tokenMarket.isActive && !tokenMarket.isPaused,
|
|
248
|
-
canBePayBacked: tokenMarket.isActive && !tokenMarket.isPaused,
|
|
249
|
-
disabledStableBorrowing: !tokenMarket.stableBorrowRateEnabled,
|
|
250
|
-
totalBorrow: assetAmountInEth(tokenMarket.totalBorrow.toString(), symbol),
|
|
251
|
-
totalBorrowVar: assetAmountInEth(tokenMarket.totalBorrowVar.toString(), symbol),
|
|
252
|
-
price: new Dec(tokenMarket.price.toString()).div(1e8).toString(), // is actually price in USD
|
|
253
|
-
isolationModeBorrowingEnabled: tokenMarket.isolationModeBorrowingEnabled,
|
|
254
|
-
isFlashLoanEnabled: tokenMarket.isFlashLoanEnabled,
|
|
255
|
-
eModeCategoryData: {
|
|
256
|
-
label: tokenMarket.label,
|
|
257
|
-
liquidationBonus: new Dec(tokenMarket.liquidationBonus).div(10000).toString(),
|
|
258
|
-
liquidationRatio: new Dec(tokenMarket.liquidationThreshold).div(10000).toString(),
|
|
259
|
-
collateralFactor: new Dec(tokenMarket.ltv).div(10000).toString(),
|
|
260
|
-
priceSource: tokenMarket.priceSource,
|
|
261
|
-
},
|
|
262
|
-
aTokenAddress: tokenMarket.aTokenAddress,
|
|
263
|
-
});
|
|
264
|
-
}));
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
await Promise.all(assetsData.map(async (_market: AaveV3AssetData) => {
|
|
268
|
-
/* eslint-disable no-param-reassign */
|
|
269
|
-
const rewardForMarket: IUiIncentiveDataProviderV3.AggregatedReserveIncentiveDataStructOutput | undefined = rewardInfo?.[_market.underlyingTokenAddress as any];
|
|
270
|
-
if (['wstETH', 'cbETH', 'rETH', 'sDAI'].includes(_market.symbol)) {
|
|
271
|
-
_market.incentiveSupplyApy = await getStakingApy(_market.symbol, defaultWeb3);
|
|
272
|
-
_market.incentiveSupplyToken = _market.symbol;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
if (_market.canBeBorrowed && _market.incentiveSupplyApy) {
|
|
276
|
-
_market.incentiveBorrowApy = `-${_market.incentiveSupplyApy}`;
|
|
277
|
-
_market.incentiveBorrowToken = _market.incentiveSupplyToken;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
if (!rewardForMarket) return;
|
|
281
|
-
const supplyRewardData = rewardForMarket.aIncentiveData.rewardsTokenInformation[0];
|
|
282
|
-
if (supplyRewardData) {
|
|
283
|
-
if (+supplyRewardData.emissionEndTimestamp * 1000 < Date.now()) return;
|
|
284
|
-
_market.incentiveSupplyToken = supplyRewardData.rewardTokenSymbol;
|
|
285
|
-
const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond;
|
|
286
|
-
const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** +supplyRewardData.priceFeedDecimals).toString();
|
|
287
|
-
_market.incentiveSupplyApy = new Dec(supplyEmissionPerSecond).div((10 ** +supplyRewardData.rewardTokenDecimals) / 100)
|
|
288
|
-
.mul(365 * 24 * 3600)
|
|
289
|
-
.mul(supplyRewardPrice)
|
|
290
|
-
.div(_market.price)
|
|
291
|
-
.div(_market.totalSupply)
|
|
292
|
-
.toString();
|
|
293
|
-
}
|
|
294
|
-
const borrowRewardData = rewardForMarket.vIncentiveData.rewardsTokenInformation[0];
|
|
295
|
-
if (borrowRewardData) {
|
|
296
|
-
if (+borrowRewardData.emissionEndTimestamp * 1000 < Date.now()) return;
|
|
297
|
-
_market.incentiveBorrowToken = borrowRewardData.rewardTokenSymbol;
|
|
298
|
-
const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond;
|
|
299
|
-
const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** +borrowRewardData.priceFeedDecimals).toString();
|
|
300
|
-
_market.incentiveBorrowApy = new Dec(supplyEmissionPerSecond).div((10 ** +borrowRewardData.rewardTokenDecimals) / 100)
|
|
301
|
-
.mul(365 * 24 * 3600)
|
|
302
|
-
.mul(supplyRewardPrice)
|
|
303
|
-
.div(_market.price)
|
|
304
|
-
.div(_market.totalBorrowVar)
|
|
305
|
-
.toString();
|
|
306
|
-
}
|
|
307
|
-
/* eslint-enable no-param-reassign */
|
|
308
|
-
}));
|
|
309
|
-
|
|
310
|
-
const payload: AaveV3AssetsData = {};
|
|
311
|
-
// Sort by market size
|
|
312
|
-
assetsData
|
|
313
|
-
.sort((a, b) => {
|
|
314
|
-
const aMarket = new Dec(a.price).times(a.totalSupply).toString();
|
|
315
|
-
const bMarket = new Dec(b.price).times(b.totalSupply).toString();
|
|
316
|
-
|
|
317
|
-
return new Dec(bMarket).minus(aMarket).toNumber();
|
|
318
|
-
})
|
|
319
|
-
.forEach((assetData: AaveV3AssetData, i) => {
|
|
320
|
-
payload[assetData.symbol] = { ...assetData, sortIndex: i };
|
|
321
|
-
});
|
|
322
|
-
|
|
323
|
-
return { assetsData: payload };
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
export const EMPTY_AAVE_DATA = {
|
|
327
|
-
usedAssets: {},
|
|
328
|
-
suppliedUsd: '0',
|
|
329
|
-
borrowedUsd: '0',
|
|
330
|
-
borrowLimitUsd: '0',
|
|
331
|
-
leftToBorrowUsd: '0',
|
|
332
|
-
ratio: '0',
|
|
333
|
-
minRatio: '0',
|
|
334
|
-
netApy: '0',
|
|
335
|
-
incentiveUsd: '0',
|
|
336
|
-
totalInterestUsd: '0',
|
|
337
|
-
isSubscribedToAutomation: false,
|
|
338
|
-
automationResubscribeRequired: false,
|
|
339
|
-
eModeCategory: 0,
|
|
340
|
-
isInIsolationMode: false,
|
|
341
|
-
isInSiloedMode: false,
|
|
342
|
-
totalSupplied: '0',
|
|
343
|
-
eModeCategories: [],
|
|
344
|
-
collRatio: '0',
|
|
345
|
-
suppliedCollateralUsd: '0',
|
|
346
|
-
};
|
|
347
|
-
|
|
348
|
-
export const getAaveV3AccountBalances = async (web3: Web3, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
|
|
349
|
-
let balances: PositionBalances = {
|
|
350
|
-
collateral: {},
|
|
351
|
-
debt: {},
|
|
352
|
-
};
|
|
353
|
-
|
|
354
|
-
if (!address) {
|
|
355
|
-
return balances;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
const loanInfoContract = AaveV3ViewContract(web3, network, block);
|
|
359
|
-
|
|
360
|
-
const market = AAVE_V3(network);
|
|
361
|
-
const marketAddress = market.providerAddress;
|
|
362
|
-
|
|
363
|
-
const protocolDataProviderContract =
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
);
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
const
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
];
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
...balances.
|
|
400
|
-
[addressMapping ? assetAddr : asset]: tokenInfo.
|
|
401
|
-
},
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
const
|
|
430
|
-
|
|
431
|
-
const
|
|
432
|
-
|
|
433
|
-
const
|
|
434
|
-
|
|
435
|
-
const
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
const
|
|
469
|
-
const
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
interestMode = '
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
borrowedVariable,
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
payload.
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
payload.
|
|
536
|
-
? new Dec(payload.
|
|
537
|
-
: '0';
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
// eslint-disable-next-line no-param-reassign
|
|
547
|
-
item.
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
};
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
const marketData = await getAaveV3MarketData(web3, network, market, mainnetWeb3);
|
|
563
|
-
const positionData = await getAaveV3AccountData(web3, network, address, { assetsData: marketData.assetsData, selectedMarket: market });
|
|
564
|
-
return positionData;
|
|
565
|
-
};
|
|
1
|
+
import Web3 from 'web3';
|
|
2
|
+
import Dec from 'decimal.js';
|
|
3
|
+
import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
|
|
4
|
+
import {
|
|
5
|
+
AaveIncentiveDataProviderV3Contract,
|
|
6
|
+
AaveV3ViewContract,
|
|
7
|
+
createContractWrapper,
|
|
8
|
+
getConfigContractAbi,
|
|
9
|
+
getConfigContractAddress,
|
|
10
|
+
GhoTokenContract,
|
|
11
|
+
} from '../contracts';
|
|
12
|
+
import {
|
|
13
|
+
addToObjectIf, ethToWeth, getAbiItem, isLayer2Network, wethToEth, wethToEthByAddress,
|
|
14
|
+
} from '../services/utils';
|
|
15
|
+
import {
|
|
16
|
+
AaveMarketInfo,
|
|
17
|
+
AaveV3AssetData,
|
|
18
|
+
AaveV3AssetsData,
|
|
19
|
+
AaveV3IncentiveData,
|
|
20
|
+
AaveV3MarketData,
|
|
21
|
+
AaveV3PositionData,
|
|
22
|
+
AaveV3UsedAsset,
|
|
23
|
+
AaveV3UsedAssets,
|
|
24
|
+
EModeCategoryDataMapping,
|
|
25
|
+
} from '../types/aave';
|
|
26
|
+
import {
|
|
27
|
+
Blockish, EthAddress, NetworkNumber, PositionBalances,
|
|
28
|
+
} from '../types/common';
|
|
29
|
+
import { calculateNetApy, getStakingApy } from '../staking';
|
|
30
|
+
import { multicall } from '../multicall';
|
|
31
|
+
import { IUiIncentiveDataProviderV3 } from '../types/contracts/generated/AaveUiIncentiveDataProviderV3';
|
|
32
|
+
import { getAssetsBalances } from '../assets';
|
|
33
|
+
import { calculateBorrowingAssetLimit } from '../moneymarket';
|
|
34
|
+
import {
|
|
35
|
+
aaveAnyGetAggregatedPositionData,
|
|
36
|
+
aaveV3IsInIsolationMode,
|
|
37
|
+
aaveV3IsInSiloedMode,
|
|
38
|
+
} from '../helpers/aaveHelpers';
|
|
39
|
+
import { AAVE_V3 } from '../markets/aave';
|
|
40
|
+
|
|
41
|
+
export const test = (web3: Web3, network: NetworkNumber) => {
|
|
42
|
+
const contract = AaveV3ViewContract(web3, 1);
|
|
43
|
+
return contract.methods.AAVE_REFERRAL_CODE().call();
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export const aaveV3CalculateDiscountRate = (
|
|
47
|
+
debtBalance: string,
|
|
48
|
+
discountTokenBalance: string,
|
|
49
|
+
discountRate: string,
|
|
50
|
+
minDiscountTokenBalance: string,
|
|
51
|
+
minGhoBalanceForDiscount: string,
|
|
52
|
+
ghoDiscountedPerDiscountToken: string,
|
|
53
|
+
) => {
|
|
54
|
+
if (new Dec(discountTokenBalance).lt(minDiscountTokenBalance) || new Dec(debtBalance).lt(minGhoBalanceForDiscount)) {
|
|
55
|
+
return '0';
|
|
56
|
+
}
|
|
57
|
+
const discountedBalance = new Dec( // wadMul
|
|
58
|
+
new Dec(discountTokenBalance).mul(ghoDiscountedPerDiscountToken).add(new Dec(1e18).div(2)),
|
|
59
|
+
).div(1e18).toDP(0);
|
|
60
|
+
|
|
61
|
+
if (new Dec(discountedBalance).gte(debtBalance)) {
|
|
62
|
+
return new Dec(discountRate).div(10000).toDP(4).toString();
|
|
63
|
+
}
|
|
64
|
+
return new Dec(discountedBalance)
|
|
65
|
+
.mul(discountRate)
|
|
66
|
+
.div(debtBalance)
|
|
67
|
+
.div(10000)
|
|
68
|
+
.toDP(4)
|
|
69
|
+
.toString();
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export const aaveV3EmodeCategoriesMapping = (extractedState: any, usedAssets: AaveV3UsedAssets) => {
|
|
73
|
+
const { assetsData }: { assetsData: AaveV3AssetsData } = extractedState;
|
|
74
|
+
const usedAssetsValues = Object.values(usedAssets);
|
|
75
|
+
|
|
76
|
+
const categoriesMapping: { [key: number]: EModeCategoryDataMapping } = {};
|
|
77
|
+
Object.values(assetsData).forEach((a: AaveV3AssetData) => {
|
|
78
|
+
const borrowingOnlyFromCategory = a.eModeCategory === 0
|
|
79
|
+
? true
|
|
80
|
+
: !usedAssetsValues.filter(u => u.isBorrowed && u.eModeCategory !== a.eModeCategory).length;
|
|
81
|
+
const afterEnteringCategory = aaveAnyGetAggregatedPositionData({
|
|
82
|
+
...extractedState, usedAssets, eModeCategory: a.eModeCategory,
|
|
83
|
+
});
|
|
84
|
+
const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent);
|
|
85
|
+
const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized];
|
|
86
|
+
|
|
87
|
+
categoriesMapping[a.eModeCategory] = {
|
|
88
|
+
enteringTerms,
|
|
89
|
+
canEnterCategory: !enteringTerms.includes(false),
|
|
90
|
+
id: a.eModeCategory,
|
|
91
|
+
data: a.eModeCategoryData,
|
|
92
|
+
assets: a.eModeCategory === 0 ? [] : [...(categoriesMapping[a.eModeCategory]?.assets || []), a.symbol],
|
|
93
|
+
enabledData: {
|
|
94
|
+
ratio: afterEnteringCategory.ratio,
|
|
95
|
+
liqRatio: afterEnteringCategory.liqRatio,
|
|
96
|
+
liqPercent: afterEnteringCategory.liqPercent,
|
|
97
|
+
collRatio: afterEnteringCategory.collRatio,
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
});
|
|
101
|
+
return categoriesMapping;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
export async function getAaveV3MarketData(web3: Web3, network: NetworkNumber, market: AaveMarketInfo, defaultWeb3: Web3): Promise<AaveV3MarketData> {
|
|
105
|
+
const _addresses = market.assets.map(a => getAssetInfo(ethToWeth(a), network).address);
|
|
106
|
+
|
|
107
|
+
const isL2 = isLayer2Network(network);
|
|
108
|
+
|
|
109
|
+
const loanInfoContract = AaveV3ViewContract(web3, network);
|
|
110
|
+
const aaveIncentivesContract = AaveIncentiveDataProviderV3Contract(web3, network);
|
|
111
|
+
const marketAddress = market.providerAddress;
|
|
112
|
+
|
|
113
|
+
const GhoDiscountRateStrategyAddress = getConfigContractAddress('GhoDiscountRateStrategy', NetworkNumber.Eth);
|
|
114
|
+
const GhoDiscountRateStrategyAbi = getConfigContractAbi('GhoDiscountRateStrategy');
|
|
115
|
+
const GhoTokenAbi = getConfigContractAbi('GHO');
|
|
116
|
+
|
|
117
|
+
const multicallCallsObject = [
|
|
118
|
+
{
|
|
119
|
+
target: GhoDiscountRateStrategyAddress,
|
|
120
|
+
abiItem: getAbiItem(GhoDiscountRateStrategyAbi, 'GHO_DISCOUNTED_PER_DISCOUNT_TOKEN'),
|
|
121
|
+
params: [],
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
target: GhoDiscountRateStrategyAddress,
|
|
125
|
+
abiItem: getAbiItem(GhoDiscountRateStrategyAbi, 'DISCOUNT_RATE'),
|
|
126
|
+
params: [],
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
target: GhoDiscountRateStrategyAddress,
|
|
130
|
+
abiItem: getAbiItem(GhoDiscountRateStrategyAbi, 'MIN_DISCOUNT_TOKEN_BALANCE'),
|
|
131
|
+
params: [],
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
target: GhoDiscountRateStrategyAddress,
|
|
135
|
+
abiItem: getAbiItem(GhoDiscountRateStrategyAbi, 'MIN_DEBT_TOKEN_BALANCE'),
|
|
136
|
+
params: [],
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
target: getAssetInfo('GHO').address,
|
|
140
|
+
abiItem: getAbiItem(GhoTokenAbi, 'getFacilitatorsList'),
|
|
141
|
+
params: [],
|
|
142
|
+
},
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
const ghoContract = GhoTokenContract(web3, network);
|
|
146
|
+
|
|
147
|
+
// eslint-disable-next-line prefer-const
|
|
148
|
+
let [loanInfo, isBorrowAllowed, multiRes] = await Promise.all([
|
|
149
|
+
loanInfoContract.methods.getFullTokensInfo(marketAddress, _addresses).call(),
|
|
150
|
+
loanInfoContract.methods.isBorrowAllowed(marketAddress).call(), // Used on L2s check for PriceOracleSentinel (mainnet will always return true)
|
|
151
|
+
isL2 ? [{ 0: null }, { 0: null }, { 0: null }, { 0: null }, { 0: null }] : multicall(multicallCallsObject, web3, network),
|
|
152
|
+
]);
|
|
153
|
+
isBorrowAllowed = isLayer2Network(network) ? isBorrowAllowed : true;
|
|
154
|
+
|
|
155
|
+
const [
|
|
156
|
+
{ 0: ghoDiscountedPerDiscountToken },
|
|
157
|
+
{ 0: discountRate },
|
|
158
|
+
{ 0: minDiscountTokenBalance },
|
|
159
|
+
{ 0: minGhoBalanceForDiscount },
|
|
160
|
+
{ 0: facilitatorsList },
|
|
161
|
+
] = multiRes;
|
|
162
|
+
|
|
163
|
+
let rewardInfo: IUiIncentiveDataProviderV3.AggregatedReserveIncentiveDataStructOutput[] | null = null;
|
|
164
|
+
if (network === 10) {
|
|
165
|
+
rewardInfo = await aaveIncentivesContract.methods.getReservesIncentivesData(marketAddress).call();
|
|
166
|
+
rewardInfo = rewardInfo.reduce((all: any, _market: AaveV3IncentiveData) => {
|
|
167
|
+
// eslint-disable-next-line no-param-reassign
|
|
168
|
+
all[_market.underlyingAsset] = _market;
|
|
169
|
+
return all;
|
|
170
|
+
}, {});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const assetsData: AaveV3AssetData[] = await Promise.all(loanInfo
|
|
174
|
+
.map(async (tokenMarket, i) => {
|
|
175
|
+
const symbol = market.assets[i];
|
|
176
|
+
const nativeAsset = symbol === 'GHO';
|
|
177
|
+
|
|
178
|
+
let borrowCap = tokenMarket.borrowCap;
|
|
179
|
+
let discountRateOnBorrow = '0';
|
|
180
|
+
|
|
181
|
+
if (nativeAsset && facilitatorsList && discountRate && minDiscountTokenBalance && minGhoBalanceForDiscount && ghoDiscountedPerDiscountToken) {
|
|
182
|
+
const facilitatorBucket = await ghoContract.methods.getFacilitatorBucket(facilitatorsList[0]).call();
|
|
183
|
+
const availableFacilitatorCap = assetAmountInEth(new Dec(facilitatorBucket[0]).sub(facilitatorBucket[1]).toString(), 'GHO');
|
|
184
|
+
|
|
185
|
+
borrowCap = Dec.min(borrowCap, availableFacilitatorCap).toString();
|
|
186
|
+
|
|
187
|
+
discountRateOnBorrow = aaveV3CalculateDiscountRate(
|
|
188
|
+
tokenMarket.totalBorrow.toString(),
|
|
189
|
+
'3160881469228662060510133', // stkAAVE total supply
|
|
190
|
+
discountRate,
|
|
191
|
+
minDiscountTokenBalance,
|
|
192
|
+
minGhoBalanceForDiscount,
|
|
193
|
+
ghoDiscountedPerDiscountToken,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
let marketLiquidity = nativeAsset
|
|
198
|
+
? assetAmountInEth(new Dec(assetAmountInWei(borrowCap.toString(), 'GHO'))
|
|
199
|
+
.sub(tokenMarket.totalBorrow.toString())
|
|
200
|
+
.toString(), symbol)
|
|
201
|
+
: assetAmountInEth(new Dec(tokenMarket.totalSupply.toString())
|
|
202
|
+
.sub(tokenMarket.totalBorrow.toString())
|
|
203
|
+
.toString(), symbol);
|
|
204
|
+
|
|
205
|
+
if (new Dec(marketLiquidity).lt(0)) {
|
|
206
|
+
marketLiquidity = '0';
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return ({
|
|
210
|
+
nativeAsset,
|
|
211
|
+
...addToObjectIf(nativeAsset, {
|
|
212
|
+
discountData: {
|
|
213
|
+
ghoDiscountedPerDiscountToken,
|
|
214
|
+
discountRate,
|
|
215
|
+
minDiscountTokenBalance,
|
|
216
|
+
minGhoBalanceForDiscount,
|
|
217
|
+
},
|
|
218
|
+
}),
|
|
219
|
+
symbol,
|
|
220
|
+
isIsolated: new Dec(tokenMarket.debtCeilingForIsolationMode).gt(0),
|
|
221
|
+
debtCeilingForIsolationMode: new Dec(tokenMarket.debtCeilingForIsolationMode).div(100).toString(),
|
|
222
|
+
isSiloed: tokenMarket.isSiloedForBorrowing,
|
|
223
|
+
eModeCategory: +tokenMarket.emodeCategory,
|
|
224
|
+
isolationModeTotalDebt: new Dec(tokenMarket.isolationModeTotalDebt).div(100).toString(),
|
|
225
|
+
assetId: Number(tokenMarket.assetId),
|
|
226
|
+
underlyingTokenAddress: tokenMarket.underlyingTokenAddress,
|
|
227
|
+
supplyRate: new Dec(tokenMarket.supplyRate.toString()).div(1e25).toString(),
|
|
228
|
+
borrowRate: new Dec(tokenMarket.borrowRateVariable.toString()).div(1e25).toString(),
|
|
229
|
+
borrowRateDiscounted: nativeAsset ? new Dec(tokenMarket.borrowRateVariable.toString()).div(1e25).mul(1 - parseFloat(discountRateOnBorrow)).toString() : '0',
|
|
230
|
+
borrowRateStable: new Dec(tokenMarket.borrowRateStable.toString()).div(1e25).toString(),
|
|
231
|
+
collateralFactor: new Dec(tokenMarket.collateralFactor.toString()).div(10000).toString(),
|
|
232
|
+
liquidationRatio: new Dec(tokenMarket.liquidationRatio.toString()).div(10000).toString(),
|
|
233
|
+
marketLiquidity,
|
|
234
|
+
utilization: new Dec(tokenMarket.totalBorrow.toString())
|
|
235
|
+
.div(new Dec(tokenMarket.totalSupply.toString()))
|
|
236
|
+
.times(100)
|
|
237
|
+
.toString(),
|
|
238
|
+
usageAsCollateralEnabled: tokenMarket.usageAsCollateralEnabled,
|
|
239
|
+
supplyCap: tokenMarket.supplyCap,
|
|
240
|
+
borrowCap,
|
|
241
|
+
totalSupply: assetAmountInEth(tokenMarket.totalSupply.toString(), symbol),
|
|
242
|
+
isInactive: !tokenMarket.isActive,
|
|
243
|
+
isFrozen: tokenMarket.isFrozen,
|
|
244
|
+
isPaused: tokenMarket.isPaused,
|
|
245
|
+
canBeBorrowed: tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen && tokenMarket.borrowingEnabled && isBorrowAllowed,
|
|
246
|
+
canBeSupplied: !nativeAsset && tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen,
|
|
247
|
+
canBeWithdrawn: tokenMarket.isActive && !tokenMarket.isPaused,
|
|
248
|
+
canBePayBacked: tokenMarket.isActive && !tokenMarket.isPaused,
|
|
249
|
+
disabledStableBorrowing: !tokenMarket.stableBorrowRateEnabled,
|
|
250
|
+
totalBorrow: assetAmountInEth(tokenMarket.totalBorrow.toString(), symbol),
|
|
251
|
+
totalBorrowVar: assetAmountInEth(tokenMarket.totalBorrowVar.toString(), symbol),
|
|
252
|
+
price: new Dec(tokenMarket.price.toString()).div(1e8).toString(), // is actually price in USD
|
|
253
|
+
isolationModeBorrowingEnabled: tokenMarket.isolationModeBorrowingEnabled,
|
|
254
|
+
isFlashLoanEnabled: tokenMarket.isFlashLoanEnabled,
|
|
255
|
+
eModeCategoryData: {
|
|
256
|
+
label: tokenMarket.label,
|
|
257
|
+
liquidationBonus: new Dec(tokenMarket.liquidationBonus).div(10000).toString(),
|
|
258
|
+
liquidationRatio: new Dec(tokenMarket.liquidationThreshold).div(10000).toString(),
|
|
259
|
+
collateralFactor: new Dec(tokenMarket.ltv).div(10000).toString(),
|
|
260
|
+
priceSource: tokenMarket.priceSource,
|
|
261
|
+
},
|
|
262
|
+
aTokenAddress: tokenMarket.aTokenAddress,
|
|
263
|
+
});
|
|
264
|
+
}));
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
await Promise.all(assetsData.map(async (_market: AaveV3AssetData) => {
|
|
268
|
+
/* eslint-disable no-param-reassign */
|
|
269
|
+
const rewardForMarket: IUiIncentiveDataProviderV3.AggregatedReserveIncentiveDataStructOutput | undefined = rewardInfo?.[_market.underlyingTokenAddress as any];
|
|
270
|
+
if (['wstETH', 'cbETH', 'rETH', 'sDAI'].includes(_market.symbol)) {
|
|
271
|
+
_market.incentiveSupplyApy = await getStakingApy(_market.symbol, defaultWeb3);
|
|
272
|
+
_market.incentiveSupplyToken = _market.symbol;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (_market.canBeBorrowed && _market.incentiveSupplyApy) {
|
|
276
|
+
_market.incentiveBorrowApy = `-${_market.incentiveSupplyApy}`;
|
|
277
|
+
_market.incentiveBorrowToken = _market.incentiveSupplyToken;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if (!rewardForMarket) return;
|
|
281
|
+
const supplyRewardData = rewardForMarket.aIncentiveData.rewardsTokenInformation[0];
|
|
282
|
+
if (supplyRewardData) {
|
|
283
|
+
if (+supplyRewardData.emissionEndTimestamp * 1000 < Date.now()) return;
|
|
284
|
+
_market.incentiveSupplyToken = supplyRewardData.rewardTokenSymbol;
|
|
285
|
+
const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond;
|
|
286
|
+
const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** +supplyRewardData.priceFeedDecimals).toString();
|
|
287
|
+
_market.incentiveSupplyApy = new Dec(supplyEmissionPerSecond).div((10 ** +supplyRewardData.rewardTokenDecimals) / 100)
|
|
288
|
+
.mul(365 * 24 * 3600)
|
|
289
|
+
.mul(supplyRewardPrice)
|
|
290
|
+
.div(_market.price)
|
|
291
|
+
.div(_market.totalSupply)
|
|
292
|
+
.toString();
|
|
293
|
+
}
|
|
294
|
+
const borrowRewardData = rewardForMarket.vIncentiveData.rewardsTokenInformation[0];
|
|
295
|
+
if (borrowRewardData) {
|
|
296
|
+
if (+borrowRewardData.emissionEndTimestamp * 1000 < Date.now()) return;
|
|
297
|
+
_market.incentiveBorrowToken = borrowRewardData.rewardTokenSymbol;
|
|
298
|
+
const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond;
|
|
299
|
+
const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** +borrowRewardData.priceFeedDecimals).toString();
|
|
300
|
+
_market.incentiveBorrowApy = new Dec(supplyEmissionPerSecond).div((10 ** +borrowRewardData.rewardTokenDecimals) / 100)
|
|
301
|
+
.mul(365 * 24 * 3600)
|
|
302
|
+
.mul(supplyRewardPrice)
|
|
303
|
+
.div(_market.price)
|
|
304
|
+
.div(_market.totalBorrowVar)
|
|
305
|
+
.toString();
|
|
306
|
+
}
|
|
307
|
+
/* eslint-enable no-param-reassign */
|
|
308
|
+
}));
|
|
309
|
+
|
|
310
|
+
const payload: AaveV3AssetsData = {};
|
|
311
|
+
// Sort by market size
|
|
312
|
+
assetsData
|
|
313
|
+
.sort((a, b) => {
|
|
314
|
+
const aMarket = new Dec(a.price).times(a.totalSupply).toString();
|
|
315
|
+
const bMarket = new Dec(b.price).times(b.totalSupply).toString();
|
|
316
|
+
|
|
317
|
+
return new Dec(bMarket).minus(aMarket).toNumber();
|
|
318
|
+
})
|
|
319
|
+
.forEach((assetData: AaveV3AssetData, i) => {
|
|
320
|
+
payload[assetData.symbol] = { ...assetData, sortIndex: i };
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
return { assetsData: payload };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export const EMPTY_AAVE_DATA = {
|
|
327
|
+
usedAssets: {},
|
|
328
|
+
suppliedUsd: '0',
|
|
329
|
+
borrowedUsd: '0',
|
|
330
|
+
borrowLimitUsd: '0',
|
|
331
|
+
leftToBorrowUsd: '0',
|
|
332
|
+
ratio: '0',
|
|
333
|
+
minRatio: '0',
|
|
334
|
+
netApy: '0',
|
|
335
|
+
incentiveUsd: '0',
|
|
336
|
+
totalInterestUsd: '0',
|
|
337
|
+
isSubscribedToAutomation: false,
|
|
338
|
+
automationResubscribeRequired: false,
|
|
339
|
+
eModeCategory: 0,
|
|
340
|
+
isInIsolationMode: false,
|
|
341
|
+
isInSiloedMode: false,
|
|
342
|
+
totalSupplied: '0',
|
|
343
|
+
eModeCategories: [],
|
|
344
|
+
collRatio: '0',
|
|
345
|
+
suppliedCollateralUsd: '0',
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
export const getAaveV3AccountBalances = async (web3: Web3, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
|
|
349
|
+
let balances: PositionBalances = {
|
|
350
|
+
collateral: {},
|
|
351
|
+
debt: {},
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
if (!address) {
|
|
355
|
+
return balances;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const loanInfoContract = AaveV3ViewContract(web3, network, block);
|
|
359
|
+
|
|
360
|
+
const market = AAVE_V3(network);
|
|
361
|
+
const marketAddress = market.providerAddress;
|
|
362
|
+
// @ts-ignore
|
|
363
|
+
const protocolDataProviderContract = createContractWrapper(web3, network, market.protocolData, market.protocolDataAddress);
|
|
364
|
+
|
|
365
|
+
const reserveTokens = await protocolDataProviderContract.methods.getAllReservesTokens().call({}, block);
|
|
366
|
+
const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
|
|
367
|
+
const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
|
|
368
|
+
|
|
369
|
+
// split addresses in half to avoid gas limit by multicall
|
|
370
|
+
const middleAddressIndex = Math.floor(_addresses.length / 2);
|
|
371
|
+
|
|
372
|
+
const multicallData = [
|
|
373
|
+
{
|
|
374
|
+
target: loanInfoContract.options.address,
|
|
375
|
+
abiItem: loanInfoContract.options.jsonInterface.find(({ name }) => name === 'getTokenBalances'),
|
|
376
|
+
params: [marketAddress, address, _addresses.slice(0, middleAddressIndex)],
|
|
377
|
+
},
|
|
378
|
+
{
|
|
379
|
+
target: loanInfoContract.options.address,
|
|
380
|
+
abiItem: loanInfoContract.options.jsonInterface.find(({ name }) => name === 'getTokenBalances'),
|
|
381
|
+
params: [marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)],
|
|
382
|
+
},
|
|
383
|
+
];
|
|
384
|
+
|
|
385
|
+
const multicallRes = await multicall(multicallData, web3, network, block);
|
|
386
|
+
|
|
387
|
+
const loanInfo = [...multicallRes[0][0], ...multicallRes[1][0]];
|
|
388
|
+
|
|
389
|
+
loanInfo.forEach((tokenInfo: any, i: number) => {
|
|
390
|
+
const asset = wethToEth(symbols[i]);
|
|
391
|
+
const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
|
|
392
|
+
|
|
393
|
+
balances = {
|
|
394
|
+
collateral: {
|
|
395
|
+
...balances.collateral,
|
|
396
|
+
[addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
|
|
397
|
+
},
|
|
398
|
+
debt: {
|
|
399
|
+
...balances.debt,
|
|
400
|
+
[addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
|
|
401
|
+
},
|
|
402
|
+
};
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
return balances;
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
export const getAaveV3AccountData = async (web3: Web3, network: NetworkNumber, address: EthAddress, extractedState: any): Promise<AaveV3PositionData> => {
|
|
409
|
+
const {
|
|
410
|
+
selectedMarket: market, assetsData,
|
|
411
|
+
} = extractedState;
|
|
412
|
+
let payload: AaveV3PositionData = {
|
|
413
|
+
...EMPTY_AAVE_DATA,
|
|
414
|
+
lastUpdated: Date.now(),
|
|
415
|
+
};
|
|
416
|
+
if (!address) {
|
|
417
|
+
// structure that this function returns is complex and dynamic so i didnt want to hardcode it in EMPTY_AAVE_DATA
|
|
418
|
+
// This case only triggers if user doesnt have proxy and data is refetched once proxy is created
|
|
419
|
+
// TODO when refactoring aave figure out if this is the best solution.
|
|
420
|
+
payload.eModeCategories = aaveV3EmodeCategoriesMapping(extractedState, {});
|
|
421
|
+
|
|
422
|
+
return payload;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const isL2 = isLayer2Network(network);
|
|
426
|
+
|
|
427
|
+
const loanInfoContract = AaveV3ViewContract(web3, network);
|
|
428
|
+
const marketAddress = market.providerAddress;
|
|
429
|
+
const _addresses = market.assets.map((a: string[]) => getAssetInfo(ethToWeth(a), network).address);
|
|
430
|
+
|
|
431
|
+
const middleAddressIndex = Math.floor(_addresses.length / 2); // split addresses in half to avoid gas limit by multicall
|
|
432
|
+
|
|
433
|
+
const LendingPoolAbi = getConfigContractAbi(market.lendingPool);
|
|
434
|
+
|
|
435
|
+
const multicallData = [
|
|
436
|
+
{
|
|
437
|
+
target: market.lendingPoolAddress,
|
|
438
|
+
abiItem: LendingPoolAbi.find(({ name }) => name === 'getUserEMode'),
|
|
439
|
+
params: [address],
|
|
440
|
+
},
|
|
441
|
+
{
|
|
442
|
+
target: loanInfoContract.options.address,
|
|
443
|
+
abiItem: loanInfoContract.options.jsonInterface.find(({ name }) => name === 'getTokenBalances'),
|
|
444
|
+
params: [marketAddress, address, _addresses.slice(0, middleAddressIndex)],
|
|
445
|
+
},
|
|
446
|
+
{
|
|
447
|
+
target: loanInfoContract.options.address,
|
|
448
|
+
abiItem: loanInfoContract.options.jsonInterface.find(({ name }) => name === 'getTokenBalances'),
|
|
449
|
+
params: [marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)],
|
|
450
|
+
},
|
|
451
|
+
];
|
|
452
|
+
|
|
453
|
+
const [multicallRes, { 0: stkAaveBalance }] = await Promise.all([
|
|
454
|
+
multicall(multicallData, web3, network),
|
|
455
|
+
isL2 ? { 0: '0' } : getAssetsBalances(['stkAAVE'], address, network, web3),
|
|
456
|
+
{ 0: '0' },
|
|
457
|
+
]);
|
|
458
|
+
|
|
459
|
+
const loanInfo = [...multicallRes[1][0], ...multicallRes[2][0]];
|
|
460
|
+
|
|
461
|
+
const usedAssets = {} as AaveV3UsedAssets;
|
|
462
|
+
loanInfo.map(async (tokenInfo, i) => {
|
|
463
|
+
const asset = market.assets[i];
|
|
464
|
+
const isSupplied = tokenInfo.balance.toString() !== '0';
|
|
465
|
+
const isBorrowed = tokenInfo.borrowsStable.toString() !== '0' || tokenInfo.borrowsVariable.toString() !== '0';
|
|
466
|
+
if (!isSupplied && !isBorrowed) return;
|
|
467
|
+
|
|
468
|
+
const supplied = assetAmountInEth(tokenInfo.balance.toString(), asset);
|
|
469
|
+
const borrowedStable = assetAmountInEth(tokenInfo.borrowsStable.toString(), asset);
|
|
470
|
+
const borrowedVariable = assetAmountInEth(tokenInfo.borrowsVariable.toString(), asset);
|
|
471
|
+
const enabledAsCollateral = assetsData[asset].usageAsCollateralEnabled ? tokenInfo.enabledAsCollateral : false;
|
|
472
|
+
|
|
473
|
+
let interestMode;
|
|
474
|
+
if (borrowedVariable === '0' && borrowedStable !== '0') {
|
|
475
|
+
interestMode = '1';
|
|
476
|
+
} else if (borrowedVariable !== '0' && borrowedStable === '0') {
|
|
477
|
+
interestMode = '2';
|
|
478
|
+
} else {
|
|
479
|
+
interestMode = 'both';
|
|
480
|
+
}
|
|
481
|
+
if (!usedAssets[asset]) usedAssets[asset] = {} as AaveV3UsedAsset;
|
|
482
|
+
const nativeAsset = asset === 'GHO';
|
|
483
|
+
|
|
484
|
+
let discountRateOnBorrow = '0';
|
|
485
|
+
const borrowed = new Dec(borrowedStable).add(borrowedVariable).toString();
|
|
486
|
+
|
|
487
|
+
if (nativeAsset && new Dec(borrowed).gt(0) && new Dec(stkAaveBalance).gt(0)) {
|
|
488
|
+
discountRateOnBorrow = aaveV3CalculateDiscountRate(
|
|
489
|
+
assetAmountInWei(borrowed, 'GHO'),
|
|
490
|
+
assetAmountInWei(stkAaveBalance, 'stkAAVE'),
|
|
491
|
+
assetsData[asset].discountData.discountRate,
|
|
492
|
+
assetsData[asset].discountData.minDiscountTokenBalance,
|
|
493
|
+
assetsData[asset].discountData.minGhoBalanceForDiscount,
|
|
494
|
+
assetsData[asset].discountData.ghoDiscountedPerDiscountToken,
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
usedAssets[asset] = {
|
|
499
|
+
...usedAssets[asset],
|
|
500
|
+
symbol: asset,
|
|
501
|
+
supplied,
|
|
502
|
+
suppliedUsd: new Dec(supplied).mul(assetsData[asset].price).toString(),
|
|
503
|
+
isSupplied,
|
|
504
|
+
collateral: enabledAsCollateral,
|
|
505
|
+
stableBorrowRate: new Dec(tokenInfo.stableBorrowRate).div(1e25).toString(),
|
|
506
|
+
discountedBorrowRate: new Dec(assetsData[asset].borrowRate).mul(1 - parseFloat(discountRateOnBorrow)).toString(),
|
|
507
|
+
borrowedStable,
|
|
508
|
+
borrowedVariable,
|
|
509
|
+
borrowedUsdStable: new Dec(borrowedStable).mul(assetsData[asset].price).toString(),
|
|
510
|
+
borrowedUsdVariable: new Dec(borrowedVariable).mul(assetsData[asset].price).toString(),
|
|
511
|
+
borrowed,
|
|
512
|
+
borrowedUsd: new Dec(new Dec(borrowedVariable).add(borrowedStable)).mul(assetsData[asset].price).toString(),
|
|
513
|
+
isBorrowed,
|
|
514
|
+
eModeCategory: assetsData[asset].eModeCategory,
|
|
515
|
+
interestMode,
|
|
516
|
+
};
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
payload.eModeCategory = +multicallRes[0][0];
|
|
520
|
+
payload = {
|
|
521
|
+
...payload,
|
|
522
|
+
usedAssets,
|
|
523
|
+
...aaveAnyGetAggregatedPositionData({
|
|
524
|
+
...extractedState, usedAssets, eModeCategory: payload.eModeCategory,
|
|
525
|
+
}),
|
|
526
|
+
};
|
|
527
|
+
payload.eModeCategories = aaveV3EmodeCategoriesMapping(extractedState, usedAssets);
|
|
528
|
+
payload.isInIsolationMode = aaveV3IsInIsolationMode({ usedAssets, assetsData });
|
|
529
|
+
payload.isInSiloedMode = aaveV3IsInSiloedMode({ usedAssets, assetsData });
|
|
530
|
+
|
|
531
|
+
payload.ratio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
532
|
+
? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
533
|
+
: '0';
|
|
534
|
+
payload.minRatio = '100';
|
|
535
|
+
payload.collRatio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
536
|
+
? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
537
|
+
: '0';
|
|
538
|
+
|
|
539
|
+
// Calculate borrow limits per asset
|
|
540
|
+
Object.values(payload.usedAssets).forEach((item) => {
|
|
541
|
+
if (item.isBorrowed) {
|
|
542
|
+
// eslint-disable-next-line no-param-reassign
|
|
543
|
+
item.stableLimit = calculateBorrowingAssetLimit(item.borrowedUsdStable, payload.borrowLimitUsd);
|
|
544
|
+
// eslint-disable-next-line no-param-reassign
|
|
545
|
+
item.variableLimit = calculateBorrowingAssetLimit(item.borrowedUsdVariable, payload.borrowLimitUsd);
|
|
546
|
+
// eslint-disable-next-line no-param-reassign
|
|
547
|
+
item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
|
|
548
|
+
}
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
payload.isSubscribedToAutomation = false;
|
|
552
|
+
payload.automationResubscribeRequired = false;
|
|
553
|
+
|
|
554
|
+
return payload;
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
export const getAaveV3FullPositionData = async (web3: Web3, network: NetworkNumber, address: string, market: AaveMarketInfo, mainnetWeb3: Web3): Promise<AaveV3PositionData> => {
|
|
558
|
+
const marketData = await getAaveV3MarketData(web3, network, market, mainnetWeb3);
|
|
559
|
+
const positionData = await getAaveV3AccountData(web3, network, address, { assetsData: marketData.assetsData, selectedMarket: market });
|
|
560
|
+
return positionData;
|
|
561
|
+
};
|