@defisaver/positions-sdk 2.1.11 → 2.1.13
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/.mocharc.json +4 -4
- package/.nvmrc +1 -1
- package/README.md +64 -64
- package/cjs/aaveV3/index.js +1 -1
- package/cjs/contracts.d.ts +100947 -134653
- package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
- package/cjs/markets/aave/marketAssets.js +1 -1
- package/cjs/services/viem.d.ts +2 -3254
- package/cjs/staking/staking.d.ts +1 -1
- package/cjs/staking/staking.js +17 -14
- package/esm/aaveV3/index.js +1 -1
- package/esm/contracts.d.ts +100947 -134653
- package/esm/helpers/morphoBlueHelpers/index.js +66 -66
- package/esm/markets/aave/marketAssets.js +1 -1
- package/esm/services/viem.d.ts +2 -3254
- package/esm/staking/staking.d.ts +1 -1
- package/esm/staking/staking.js +17 -14
- package/package.json +47 -47
- package/src/aaveV2/index.ts +240 -240
- package/src/aaveV3/index.ts +614 -614
- package/src/aaveV3/merit.ts +97 -97
- package/src/aaveV3/merkl.ts +74 -74
- package/src/claiming/aaveV3.ts +154 -154
- package/src/claiming/compV3.ts +22 -22
- package/src/claiming/index.ts +12 -12
- package/src/claiming/king.ts +66 -66
- package/src/claiming/morphoBlue.ts +118 -118
- package/src/claiming/spark.ts +225 -225
- package/src/compoundV2/index.ts +244 -244
- package/src/compoundV3/index.ts +274 -274
- package/src/config/contracts.ts +1251 -1251
- package/src/constants/index.ts +10 -10
- package/src/contracts.ts +120 -120
- package/src/curveUsd/index.ts +254 -254
- package/src/eulerV2/index.ts +324 -324
- package/src/exchange/index.ts +25 -25
- package/src/fluid/index.ts +1668 -1668
- package/src/helpers/aaveHelpers/index.ts +187 -187
- package/src/helpers/compoundHelpers/index.ts +283 -283
- package/src/helpers/curveUsdHelpers/index.ts +40 -40
- package/src/helpers/eulerHelpers/index.ts +222 -222
- package/src/helpers/fluidHelpers/index.ts +326 -326
- package/src/helpers/index.ts +10 -10
- package/src/helpers/liquityV2Helpers/index.ts +82 -82
- package/src/helpers/llamaLendHelpers/index.ts +53 -53
- package/src/helpers/makerHelpers/index.ts +52 -52
- package/src/helpers/morphoBlueHelpers/index.ts +396 -396
- package/src/helpers/sparkHelpers/index.ts +158 -158
- package/src/index.ts +47 -47
- package/src/liquity/index.ts +159 -159
- package/src/liquityV2/index.ts +657 -657
- package/src/llamaLend/index.ts +305 -305
- package/src/maker/index.ts +223 -223
- package/src/markets/aave/index.ts +116 -116
- package/src/markets/aave/marketAssets.ts +54 -54
- package/src/markets/compound/index.ts +238 -238
- package/src/markets/compound/marketsAssets.ts +97 -97
- package/src/markets/curveUsd/index.ts +69 -69
- package/src/markets/euler/index.ts +26 -26
- package/src/markets/fluid/index.ts +2460 -2460
- package/src/markets/index.ts +25 -25
- package/src/markets/liquityV2/index.ts +102 -102
- package/src/markets/llamaLend/contractAddresses.ts +141 -141
- package/src/markets/llamaLend/index.ts +235 -235
- package/src/markets/morphoBlue/index.ts +895 -895
- package/src/markets/spark/index.ts +29 -29
- package/src/markets/spark/marketAssets.ts +12 -12
- package/src/moneymarket/moneymarketCommonService.ts +80 -80
- package/src/morphoBlue/index.ts +274 -274
- package/src/portfolio/index.ts +570 -570
- package/src/services/priceService.ts +159 -159
- package/src/services/utils.ts +115 -115
- package/src/services/viem.ts +34 -34
- package/src/setup.ts +8 -8
- package/src/spark/index.ts +456 -456
- package/src/staking/eligibility.ts +53 -53
- package/src/staking/index.ts +1 -1
- package/src/staking/staking.ts +177 -172
- package/src/types/aave.ts +189 -189
- package/src/types/claiming.ts +109 -109
- package/src/types/common.ts +107 -107
- package/src/types/compound.ts +136 -136
- package/src/types/curveUsd.ts +123 -123
- package/src/types/euler.ts +175 -175
- package/src/types/fluid.ts +452 -452
- package/src/types/index.ts +13 -13
- package/src/types/liquity.ts +30 -30
- package/src/types/liquityV2.ts +126 -126
- package/src/types/llamaLend.ts +159 -159
- package/src/types/maker.ts +63 -63
- package/src/types/merit.ts +1 -1
- package/src/types/merkl.ts +70 -70
- package/src/types/morphoBlue.ts +194 -194
- package/src/types/portfolio.ts +60 -60
- package/src/types/spark.ts +133 -133
- package/src/umbrella/index.ts +69 -69
- package/src/umbrella/umbrellaUtils.ts +29 -29
package/src/aaveV3/index.ts
CHANGED
|
@@ -1,614 +1,614 @@
|
|
|
1
|
-
import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
|
|
2
|
-
import { Client } from 'viem';
|
|
3
|
-
import Dec from 'decimal.js';
|
|
4
|
-
import {
|
|
5
|
-
AaveIncentiveDataProviderV3ContractViem,
|
|
6
|
-
AaveIncentivesControllerViem,
|
|
7
|
-
AaveV3ViewContractViem,
|
|
8
|
-
createViemContractFromConfigFunc,
|
|
9
|
-
StkAAVEViem,
|
|
10
|
-
} from '../contracts';
|
|
11
|
-
import { aaveAnyGetAggregatedPositionData, aaveV3IsInIsolationMode, aaveV3IsInSiloedMode } from '../helpers/aaveHelpers';
|
|
12
|
-
import { AAVE_V3 } from '../markets/aave';
|
|
13
|
-
import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
|
|
14
|
-
import {
|
|
15
|
-
getWrappedNativeAssetFromUnwrapped, isEnabledOnBitmap, isLayer2Network, wethToEth, wethToEthByAddress,
|
|
16
|
-
} from '../services/utils';
|
|
17
|
-
import { getStakingApy, STAKING_ASSETS } from '../staking';
|
|
18
|
-
import {
|
|
19
|
-
AaveMarketInfo,
|
|
20
|
-
AaveV3AssetData,
|
|
21
|
-
AaveV3AssetsData,
|
|
22
|
-
AaveV3MarketData,
|
|
23
|
-
AaveV3PositionData,
|
|
24
|
-
AaveV3UsedAsset,
|
|
25
|
-
AaveV3UsedAssets,
|
|
26
|
-
EModeCategoriesData,
|
|
27
|
-
EModeCategoryData,
|
|
28
|
-
EModeCategoryDataMapping,
|
|
29
|
-
} from '../types/aave';
|
|
30
|
-
import {
|
|
31
|
-
Blockish, EthAddress, EthereumProvider, IncentiveEligibilityId, IncentiveKind, NetworkNumber, PositionBalances, HexString,
|
|
32
|
-
} from '../types/common';
|
|
33
|
-
import { getViemProvider, setViemBlockNumber } from '../services/viem';
|
|
34
|
-
import { getMeritCampaigns } from './merit';
|
|
35
|
-
import { getAaveUnderlyingSymbol, getMerkleCampaigns } from './merkl';
|
|
36
|
-
import { SECONDS_PER_DAY, SECONDS_PER_YEAR } from '../constants';
|
|
37
|
-
|
|
38
|
-
export const aaveV3EmodeCategoriesMapping = (extractedState: any, usedAssets: AaveV3UsedAssets) => {
|
|
39
|
-
const { eModeCategoriesData }: { assetsData: AaveV3AssetsData, eModeCategoriesData: EModeCategoriesData } = extractedState;
|
|
40
|
-
const usedAssetsValues = Object.values(usedAssets);
|
|
41
|
-
|
|
42
|
-
const categoriesMapping: { [key: number]: EModeCategoryDataMapping } = {};
|
|
43
|
-
|
|
44
|
-
Object.values(eModeCategoriesData).forEach((e: EModeCategoryData) => {
|
|
45
|
-
const borrowingOnlyFromCategory = e.id === 0
|
|
46
|
-
? true
|
|
47
|
-
: !usedAssetsValues.filter(u => u.isBorrowed && !e.borrowAssets.includes(u.symbol)).length;
|
|
48
|
-
const afterEnteringCategory = aaveAnyGetAggregatedPositionData({
|
|
49
|
-
...extractedState, usedAssets, eModeCategory: e.id,
|
|
50
|
-
});
|
|
51
|
-
const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent);
|
|
52
|
-
const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized];
|
|
53
|
-
categoriesMapping[e.id] = {
|
|
54
|
-
enteringTerms,
|
|
55
|
-
canEnterCategory: !enteringTerms.includes(false),
|
|
56
|
-
id: e.id,
|
|
57
|
-
enabledData: {
|
|
58
|
-
ratio: afterEnteringCategory.ratio,
|
|
59
|
-
liqRatio: afterEnteringCategory.liqRatio,
|
|
60
|
-
liqPercent: afterEnteringCategory.liqPercent,
|
|
61
|
-
collRatio: afterEnteringCategory.collRatio,
|
|
62
|
-
},
|
|
63
|
-
};
|
|
64
|
-
});
|
|
65
|
-
return categoriesMapping;
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
export async function _getAaveV3MarketData(provider: Client, network: NetworkNumber, market: AaveMarketInfo, blockNumber: 'latest' | number = 'latest'): Promise<AaveV3MarketData> {
|
|
69
|
-
const _addresses = market.assets.map(a => getAssetInfo(getWrappedNativeAssetFromUnwrapped(a), network).address);
|
|
70
|
-
|
|
71
|
-
const isL2 = isLayer2Network(network);
|
|
72
|
-
const loanInfoContract = AaveV3ViewContractViem(provider, network);
|
|
73
|
-
const aaveIncentivesContract = AaveIncentiveDataProviderV3ContractViem(provider, network);
|
|
74
|
-
const marketAddress = market.providerAddress;
|
|
75
|
-
const networksWithIncentives = [NetworkNumber.Eth, NetworkNumber.Arb, NetworkNumber.Opt, NetworkNumber.Linea, NetworkNumber.Plasma];
|
|
76
|
-
|
|
77
|
-
// eslint-disable-next-line prefer-const
|
|
78
|
-
let [loanInfo, eModesInfo, isBorrowAllowed, rewardInfo, merkleRewardsMap, meritRewardsMap] = await Promise.all([
|
|
79
|
-
loanInfoContract.read.getFullTokensInfo([marketAddress, _addresses as EthAddress[]], setViemBlockNumber(blockNumber)),
|
|
80
|
-
loanInfoContract.read.getAllEmodes([marketAddress], setViemBlockNumber(blockNumber)),
|
|
81
|
-
loanInfoContract.read.isBorrowAllowed([marketAddress], setViemBlockNumber(blockNumber)), // Used on L2s check for PriceOracleSentinel (mainnet will always return true)
|
|
82
|
-
networksWithIncentives.includes(network) ? aaveIncentivesContract.read.getReservesIncentivesData([marketAddress], setViemBlockNumber(blockNumber)) : null,
|
|
83
|
-
getMerkleCampaigns(network),
|
|
84
|
-
getMeritCampaigns(network, market.value),
|
|
85
|
-
]);
|
|
86
|
-
isBorrowAllowed = isLayer2Network(network) ? isBorrowAllowed : true;
|
|
87
|
-
|
|
88
|
-
const eModeCategoriesData: EModeCategoriesData = {};
|
|
89
|
-
for (let i = 0; i < eModesInfo.length; i++) {
|
|
90
|
-
if (!eModesInfo[i].label) break;
|
|
91
|
-
eModeCategoriesData[i + 1] = {
|
|
92
|
-
label: eModesInfo[i].label,
|
|
93
|
-
id: i + 1,
|
|
94
|
-
liquidationBonus: new Dec(eModesInfo[i].liquidationBonus).div(10000).toString(),
|
|
95
|
-
liquidationRatio: new Dec(eModesInfo[i].liquidationThreshold).div(10000).toString(),
|
|
96
|
-
collateralFactor: new Dec(eModesInfo[i].ltv).div(10000).toString(),
|
|
97
|
-
borrowableBitmap: eModesInfo[i].borrowableBitmap.toString(),
|
|
98
|
-
collateralBitmap: eModesInfo[i].collateralBitmap.toString(),
|
|
99
|
-
borrowAssets: [],
|
|
100
|
-
collateralAssets: [],
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
if (networksWithIncentives.includes(network) && rewardInfo) {
|
|
105
|
-
rewardInfo = rewardInfo.reduce((all: any, _market: any) => {
|
|
106
|
-
// eslint-disable-next-line no-param-reassign
|
|
107
|
-
all[_market.underlyingAsset] = _market;
|
|
108
|
-
return all;
|
|
109
|
-
}, {});
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
const assetsData: AaveV3AssetData[] = await Promise.all(loanInfo
|
|
113
|
-
.map(async (tokenMarket, i) => {
|
|
114
|
-
const symbol = market.assets[i];
|
|
115
|
-
|
|
116
|
-
// eslint-disable-next-line guard-for-in
|
|
117
|
-
for (const eModeIndex in eModeCategoriesData) {
|
|
118
|
-
if (isEnabledOnBitmap(Number(eModeCategoriesData[eModeIndex].collateralBitmap), Number(tokenMarket.assetId))) eModeCategoriesData[eModeIndex].collateralAssets.push(symbol);
|
|
119
|
-
if (isEnabledOnBitmap(Number(eModeCategoriesData[eModeIndex].borrowableBitmap), Number(tokenMarket.assetId))) eModeCategoriesData[eModeIndex].borrowAssets.push(symbol);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const borrowCap = tokenMarket.borrowCap.toString();
|
|
123
|
-
|
|
124
|
-
const borrowCapInWei = new Dec(assetAmountInWei(borrowCap, symbol));
|
|
125
|
-
let marketLiquidity = borrowCapInWei.lt(new Dec(tokenMarket.totalSupply.toString()))
|
|
126
|
-
? assetAmountInEth(borrowCapInWei
|
|
127
|
-
.sub(tokenMarket.totalBorrow.toString())
|
|
128
|
-
.toString(), symbol)
|
|
129
|
-
: assetAmountInEth(new Dec(tokenMarket.totalSupply.toString())
|
|
130
|
-
.sub(tokenMarket.totalBorrow.toString())
|
|
131
|
-
.toString(), symbol);
|
|
132
|
-
|
|
133
|
-
if (new Dec(marketLiquidity).lt(0)) {
|
|
134
|
-
marketLiquidity = '0';
|
|
135
|
-
}
|
|
136
|
-
return ({
|
|
137
|
-
symbol,
|
|
138
|
-
isIsolated: new Dec(tokenMarket.debtCeilingForIsolationMode.toString()).gt(0),
|
|
139
|
-
debtCeilingForIsolationMode: new Dec(tokenMarket.debtCeilingForIsolationMode.toString()).div(100).toString(),
|
|
140
|
-
isSiloed: tokenMarket.isSiloedForBorrowing,
|
|
141
|
-
isolationModeTotalDebt: new Dec(tokenMarket.isolationModeTotalDebt.toString()).div(100).toString(),
|
|
142
|
-
assetId: Number(tokenMarket.assetId),
|
|
143
|
-
underlyingTokenAddress: tokenMarket.underlyingTokenAddress,
|
|
144
|
-
supplyRate: aprToApy(new Dec(tokenMarket.supplyRate.toString()).div(1e25).toString()),
|
|
145
|
-
borrowRate: aprToApy(new Dec(tokenMarket.borrowRateVariable.toString()).div(1e25).toString()),
|
|
146
|
-
borrowRateStable: aprToApy(new Dec(tokenMarket.borrowRateStable.toString()).div(1e25).toString()),
|
|
147
|
-
collateralFactor: new Dec(tokenMarket.collateralFactor.toString()).div(10000).toString(),
|
|
148
|
-
liquidationBonus: new Dec(tokenMarket.liquidationBonus.toString()).div(10000).toString(),
|
|
149
|
-
liquidationRatio: new Dec(tokenMarket.liquidationRatio.toString()).div(10000).toString(),
|
|
150
|
-
marketLiquidity,
|
|
151
|
-
utilization: new Dec(tokenMarket.totalBorrow.toString()).times(100).div(new Dec(tokenMarket.totalSupply.toString())).toString(),
|
|
152
|
-
usageAsCollateralEnabled: tokenMarket.usageAsCollateralEnabled,
|
|
153
|
-
supplyCap: tokenMarket.supplyCap.toString(),
|
|
154
|
-
borrowCap,
|
|
155
|
-
totalSupply: assetAmountInEth(tokenMarket.totalSupply.toString(), symbol),
|
|
156
|
-
isInactive: !tokenMarket.isActive,
|
|
157
|
-
isFrozen: tokenMarket.isFrozen,
|
|
158
|
-
isPaused: tokenMarket.isPaused,
|
|
159
|
-
canBeBorrowed: tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen && tokenMarket.borrowingEnabled && isBorrowAllowed,
|
|
160
|
-
canBeSupplied: tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen,
|
|
161
|
-
canBeWithdrawn: tokenMarket.isActive && !tokenMarket.isPaused,
|
|
162
|
-
canBePayBacked: tokenMarket.isActive && !tokenMarket.isPaused,
|
|
163
|
-
disabledStableBorrowing: !tokenMarket.stableBorrowRateEnabled,
|
|
164
|
-
totalBorrow: assetAmountInEth(tokenMarket.totalBorrow.toString(), symbol),
|
|
165
|
-
totalBorrowVar: assetAmountInEth(tokenMarket.totalBorrowVar.toString(), symbol),
|
|
166
|
-
price: new Dec(tokenMarket.price.toString()).div(1e8).toString(), // is actually price in USD
|
|
167
|
-
isolationModeBorrowingEnabled: tokenMarket.isolationModeBorrowingEnabled,
|
|
168
|
-
isFlashLoanEnabled: tokenMarket.isFlashLoanEnabled,
|
|
169
|
-
aTokenAddress: tokenMarket.aTokenAddress,
|
|
170
|
-
vTokenAddress: tokenMarket.debtTokenAddress,
|
|
171
|
-
supplyIncentives: [],
|
|
172
|
-
borrowIncentives: [],
|
|
173
|
-
});
|
|
174
|
-
}),
|
|
175
|
-
);
|
|
176
|
-
|
|
177
|
-
// Get incentives data
|
|
178
|
-
await Promise.all(assetsData.map(async (_market: AaveV3AssetData, index) => {
|
|
179
|
-
/* eslint-disable no-param-reassign */
|
|
180
|
-
// @ts-ignore
|
|
181
|
-
const rewardForMarket = rewardInfo?.[_market.underlyingTokenAddress];
|
|
182
|
-
const isStakingAsset = STAKING_ASSETS.includes(_market.symbol);
|
|
183
|
-
|
|
184
|
-
if (isStakingAsset) {
|
|
185
|
-
const yieldApy = await getStakingApy(_market.symbol);
|
|
186
|
-
_market.supplyIncentives.push({
|
|
187
|
-
apy: yieldApy,
|
|
188
|
-
token: _market.symbol,
|
|
189
|
-
incentiveKind: IncentiveKind.Staking,
|
|
190
|
-
description: `Native ${_market.symbol} yield.`,
|
|
191
|
-
});
|
|
192
|
-
if (_market.canBeBorrowed) {
|
|
193
|
-
// when borrowing assets whose value increases over time
|
|
194
|
-
_market.borrowIncentives.push({
|
|
195
|
-
apy: new Dec(yieldApy).mul(-1).toString(),
|
|
196
|
-
token: _market.symbol,
|
|
197
|
-
incentiveKind: IncentiveKind.Reward,
|
|
198
|
-
description: `Due to the native yield of ${_market.symbol}, the value of the debt would increase over time.`,
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const aTokenAddress = (_market as any).aTokenAddress.toLowerCase(); // DEV: Should aTokenAddress be in AaveV3AssetData type?
|
|
204
|
-
if (merkleRewardsMap[aTokenAddress]?.supply) {
|
|
205
|
-
const {
|
|
206
|
-
apy, rewardTokenSymbol, description, identifier,
|
|
207
|
-
} = merkleRewardsMap[aTokenAddress].supply;
|
|
208
|
-
_market.supplyIncentives.push({
|
|
209
|
-
apy,
|
|
210
|
-
token: rewardTokenSymbol,
|
|
211
|
-
incentiveKind: IncentiveKind.Reward,
|
|
212
|
-
description,
|
|
213
|
-
eligibilityId: identifier as IncentiveEligibilityId,
|
|
214
|
-
});
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
const vTokenAddress = (_market as any).vTokenAddress.toLowerCase(); // DEV: Should vTokenAddress be in AaveV3AssetData type?
|
|
218
|
-
if (merkleRewardsMap[vTokenAddress]?.borrow) {
|
|
219
|
-
const {
|
|
220
|
-
apy, rewardTokenSymbol, description, identifier,
|
|
221
|
-
} = merkleRewardsMap[vTokenAddress].borrow;
|
|
222
|
-
_market.borrowIncentives.push({
|
|
223
|
-
apy,
|
|
224
|
-
token: rewardTokenSymbol,
|
|
225
|
-
incentiveKind: IncentiveKind.Reward,
|
|
226
|
-
description,
|
|
227
|
-
eligibilityId: identifier as IncentiveEligibilityId,
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
if (meritRewardsMap.supply[_market.symbol]) {
|
|
232
|
-
const { apy, rewardTokenSymbol, description } = meritRewardsMap.supply[_market.symbol];
|
|
233
|
-
_market.supplyIncentives.push({
|
|
234
|
-
apy,
|
|
235
|
-
token: rewardTokenSymbol,
|
|
236
|
-
incentiveKind: IncentiveKind.Reward,
|
|
237
|
-
description,
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
if (meritRewardsMap.borrow[_market.symbol]) {
|
|
242
|
-
const { apy, rewardTokenSymbol, description } = meritRewardsMap.borrow[_market.symbol];
|
|
243
|
-
_market.borrowIncentives.push({
|
|
244
|
-
apy,
|
|
245
|
-
token: rewardTokenSymbol,
|
|
246
|
-
incentiveKind: IncentiveKind.Reward,
|
|
247
|
-
description,
|
|
248
|
-
});
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
if (!rewardForMarket) return;
|
|
252
|
-
// @ts-ignore
|
|
253
|
-
rewardForMarket.aIncentiveData.rewardsTokenInformation.forEach(supplyRewardData => {
|
|
254
|
-
if (supplyRewardData) {
|
|
255
|
-
if (+(supplyRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return;
|
|
256
|
-
// reward token is aave asset
|
|
257
|
-
const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond;
|
|
258
|
-
const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** +supplyRewardData.priceFeedDecimals)
|
|
259
|
-
.toString();
|
|
260
|
-
const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** +supplyRewardData.rewardTokenDecimals) / 100)
|
|
261
|
-
.mul(365 * 24 * 3600)
|
|
262
|
-
.mul(supplyRewardPrice)
|
|
263
|
-
.div(_market.price)
|
|
264
|
-
.div(_market.totalSupply)
|
|
265
|
-
.toString();
|
|
266
|
-
_market.supplyIncentives.push({
|
|
267
|
-
token: getAaveUnderlyingSymbol(supplyRewardData.rewardTokenSymbol),
|
|
268
|
-
apy: rewardApy,
|
|
269
|
-
incentiveKind: IncentiveKind.Reward,
|
|
270
|
-
description: 'Eligible for protocol-level incentives.',
|
|
271
|
-
});
|
|
272
|
-
}
|
|
273
|
-
});
|
|
274
|
-
// @ts-ignore
|
|
275
|
-
rewardForMarket.vIncentiveData.rewardsTokenInformation.forEach(borrowRewardData => {
|
|
276
|
-
if (borrowRewardData) {
|
|
277
|
-
if (+(borrowRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return;
|
|
278
|
-
const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond;
|
|
279
|
-
const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** +borrowRewardData.priceFeedDecimals)
|
|
280
|
-
.toString();
|
|
281
|
-
const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** +borrowRewardData.rewardTokenDecimals) / 100)
|
|
282
|
-
.mul(365 * 24 * 3600)
|
|
283
|
-
.mul(supplyRewardPrice)
|
|
284
|
-
.div(_market.price)
|
|
285
|
-
.div(_market.totalBorrowVar)
|
|
286
|
-
.toString();
|
|
287
|
-
_market.borrowIncentives.push({
|
|
288
|
-
token: getAaveUnderlyingSymbol(borrowRewardData.rewardTokenSymbol),
|
|
289
|
-
apy: rewardApy,
|
|
290
|
-
incentiveKind: IncentiveKind.Reward,
|
|
291
|
-
description: 'Eligible for protocol-level incentives.',
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
|
-
});
|
|
295
|
-
}));
|
|
296
|
-
|
|
297
|
-
const payload: AaveV3AssetsData = {};
|
|
298
|
-
// Sort by market size
|
|
299
|
-
assetsData
|
|
300
|
-
.sort((a, b) => {
|
|
301
|
-
const aMarket = new Dec(a.price).times(a.totalSupply).toString();
|
|
302
|
-
const bMarket = new Dec(b.price).times(b.totalSupply).toString();
|
|
303
|
-
|
|
304
|
-
return new Dec(bMarket).minus(aMarket).toNumber();
|
|
305
|
-
})
|
|
306
|
-
.forEach((assetData: AaveV3AssetData, i) => {
|
|
307
|
-
payload[assetData.symbol] = { ...assetData, sortIndex: i };
|
|
308
|
-
});
|
|
309
|
-
|
|
310
|
-
eModeCategoriesData[0] = {
|
|
311
|
-
id: 0,
|
|
312
|
-
label: '',
|
|
313
|
-
liquidationBonus: '0',
|
|
314
|
-
liquidationRatio: '0',
|
|
315
|
-
collateralFactor: '0',
|
|
316
|
-
collateralAssets: assetsData.map((a) => a.symbol),
|
|
317
|
-
borrowAssets: assetsData.map((a) => a.symbol),
|
|
318
|
-
};
|
|
319
|
-
|
|
320
|
-
return { assetsData: payload, eModeCategoriesData };
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
export async function getAaveV3MarketData(provider: EthereumProvider, network: NetworkNumber, market: AaveMarketInfo, blockNumber: 'latest' | number = 'latest'): Promise<AaveV3MarketData> {
|
|
324
|
-
return _getAaveV3MarketData(getViemProvider(provider, network), network, market, blockNumber);
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
export const EMPTY_AAVE_DATA = {
|
|
328
|
-
usedAssets: {},
|
|
329
|
-
suppliedUsd: '0',
|
|
330
|
-
borrowedUsd: '0',
|
|
331
|
-
borrowLimitUsd: '0',
|
|
332
|
-
leftToBorrowUsd: '0',
|
|
333
|
-
ratio: '0',
|
|
334
|
-
minRatio: '0',
|
|
335
|
-
netApy: '0',
|
|
336
|
-
incentiveUsd: '0',
|
|
337
|
-
totalInterestUsd: '0',
|
|
338
|
-
isSubscribedToAutomation: false,
|
|
339
|
-
automationResubscribeRequired: false,
|
|
340
|
-
eModeCategory: 0,
|
|
341
|
-
isInIsolationMode: false,
|
|
342
|
-
isInSiloedMode: false,
|
|
343
|
-
totalSupplied: '0',
|
|
344
|
-
eModeCategories: [],
|
|
345
|
-
collRatio: '0',
|
|
346
|
-
suppliedCollateralUsd: '0',
|
|
347
|
-
};
|
|
348
|
-
|
|
349
|
-
export const _getAaveV3AccountBalances = async (provider: Client, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
|
|
350
|
-
let balances: PositionBalances = {
|
|
351
|
-
collateral: {},
|
|
352
|
-
debt: {},
|
|
353
|
-
};
|
|
354
|
-
|
|
355
|
-
if (!address) {
|
|
356
|
-
return balances;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
const loanInfoContract = AaveV3ViewContractViem(provider, network, block);
|
|
360
|
-
|
|
361
|
-
const market = AAVE_V3(network);
|
|
362
|
-
const marketAddress = market.providerAddress;
|
|
363
|
-
// @ts-ignore
|
|
364
|
-
const protocolDataProviderContract = createViemContractFromConfigFunc(market.protocolData, market.protocolDataAddress)(provider, network);
|
|
365
|
-
|
|
366
|
-
// @ts-ignore
|
|
367
|
-
const reserveTokens = await protocolDataProviderContract.read.getAllReservesTokens(setViemBlockNumber(block)) as { symbol: string, tokenAddress: EthAddress }[];
|
|
368
|
-
const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
|
|
369
|
-
const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
|
|
370
|
-
|
|
371
|
-
// split addresses in half to avoid gas limit by multicall
|
|
372
|
-
const middleAddressIndex = Math.floor(_addresses.length / 2);
|
|
373
|
-
|
|
374
|
-
const [tokenBalances1, tokenBalances2] = await Promise.all([
|
|
375
|
-
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex)], setViemBlockNumber(block)),
|
|
376
|
-
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)], setViemBlockNumber(block)),
|
|
377
|
-
]);
|
|
378
|
-
|
|
379
|
-
const loanInfo = [...tokenBalances1, ...tokenBalances2];
|
|
380
|
-
|
|
381
|
-
loanInfo.forEach((tokenInfo: any, i: number) => {
|
|
382
|
-
const asset = wethToEth(symbols[i]);
|
|
383
|
-
const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
|
|
384
|
-
|
|
385
|
-
balances = {
|
|
386
|
-
collateral: {
|
|
387
|
-
...balances.collateral,
|
|
388
|
-
[addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
|
|
389
|
-
},
|
|
390
|
-
debt: {
|
|
391
|
-
...balances.debt,
|
|
392
|
-
[addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
|
|
393
|
-
},
|
|
394
|
-
};
|
|
395
|
-
});
|
|
396
|
-
|
|
397
|
-
return balances;
|
|
398
|
-
};
|
|
399
|
-
|
|
400
|
-
export const getAaveV3AccountBalances = async (provider: EthereumProvider, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => _getAaveV3AccountBalances(getViemProvider(provider, network), network, block, addressMapping, address);
|
|
401
|
-
|
|
402
|
-
export const _getAaveV3AccountData = async (provider: Client, network: NetworkNumber, address: EthAddress, extractedState: any, blockNumber: 'latest' | number = 'latest'): Promise<AaveV3PositionData> => {
|
|
403
|
-
const {
|
|
404
|
-
selectedMarket: market, assetsData,
|
|
405
|
-
} = extractedState;
|
|
406
|
-
let payload: AaveV3PositionData = {
|
|
407
|
-
...EMPTY_AAVE_DATA,
|
|
408
|
-
lastUpdated: Date.now(),
|
|
409
|
-
};
|
|
410
|
-
if (!address) {
|
|
411
|
-
return payload;
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
const loanInfoContract = AaveV3ViewContractViem(provider, network);
|
|
415
|
-
const lendingPoolContract = createViemContractFromConfigFunc(market.lendingPool, market.lendingPoolAddress)(provider, network);
|
|
416
|
-
const marketAddress = market.providerAddress;
|
|
417
|
-
const _addresses = market.assets.map((a: string) => getAssetInfo(getWrappedNativeAssetFromUnwrapped(a), network).address);
|
|
418
|
-
|
|
419
|
-
const middleAddressIndex = Math.floor(_addresses.length / 2); // split addresses in half to avoid gas limit by multicall
|
|
420
|
-
|
|
421
|
-
const [eModeCategory, tokenBalances1, tokenBalances2] = await Promise.all([
|
|
422
|
-
lendingPoolContract.read.getUserEMode([address], setViemBlockNumber(blockNumber)),
|
|
423
|
-
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex) as EthAddress[]], setViemBlockNumber(blockNumber)),
|
|
424
|
-
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length) as EthAddress[]], setViemBlockNumber(blockNumber)),
|
|
425
|
-
]);
|
|
426
|
-
|
|
427
|
-
const loanInfo = [...tokenBalances1, ...tokenBalances2];
|
|
428
|
-
|
|
429
|
-
const usedAssets = {} as AaveV3UsedAssets;
|
|
430
|
-
loanInfo.map(async (tokenInfo, i) => {
|
|
431
|
-
const asset = market.assets[i];
|
|
432
|
-
const isSupplied = tokenInfo.balance.toString() !== '0';
|
|
433
|
-
const isBorrowed = tokenInfo.borrowsStable.toString() !== '0' || tokenInfo.borrowsVariable.toString() !== '0';
|
|
434
|
-
if (!isSupplied && !isBorrowed) return;
|
|
435
|
-
|
|
436
|
-
const supplied = assetAmountInEth(tokenInfo.balance.toString(), asset);
|
|
437
|
-
const borrowedStable = assetAmountInEth(tokenInfo.borrowsStable.toString(), asset);
|
|
438
|
-
const borrowedVariable = assetAmountInEth(tokenInfo.borrowsVariable.toString(), asset);
|
|
439
|
-
const enabledAsCollateral = assetsData[asset].usageAsCollateralEnabled ? tokenInfo.enabledAsCollateral : false;
|
|
440
|
-
|
|
441
|
-
let interestMode;
|
|
442
|
-
if (borrowedVariable === '0' && borrowedStable !== '0') {
|
|
443
|
-
interestMode = '1';
|
|
444
|
-
} else if (borrowedVariable !== '0' && borrowedStable === '0') {
|
|
445
|
-
interestMode = '2';
|
|
446
|
-
} else {
|
|
447
|
-
interestMode = 'both';
|
|
448
|
-
}
|
|
449
|
-
if (!usedAssets[asset]) usedAssets[asset] = {} as AaveV3UsedAsset;
|
|
450
|
-
const borrowed = new Dec(borrowedStable).add(borrowedVariable).toString();
|
|
451
|
-
|
|
452
|
-
usedAssets[asset] = {
|
|
453
|
-
...usedAssets[asset],
|
|
454
|
-
symbol: asset,
|
|
455
|
-
supplied,
|
|
456
|
-
suppliedUsd: new Dec(supplied).mul(assetsData[asset].price).toString(),
|
|
457
|
-
isSupplied,
|
|
458
|
-
collateral: enabledAsCollateral,
|
|
459
|
-
stableBorrowRate: aprToApy(new Dec(tokenInfo.stableBorrowRate.toString()).div(1e25).toString()),
|
|
460
|
-
borrowedStable,
|
|
461
|
-
borrowedVariable,
|
|
462
|
-
borrowedUsdStable: new Dec(borrowedStable).mul(assetsData[asset].price).toString(),
|
|
463
|
-
borrowedUsdVariable: new Dec(borrowedVariable).mul(assetsData[asset].price).toString(),
|
|
464
|
-
borrowed,
|
|
465
|
-
borrowedUsd: new Dec(new Dec(borrowedVariable).add(borrowedStable)).mul(assetsData[asset].price).toString(),
|
|
466
|
-
isBorrowed,
|
|
467
|
-
interestMode,
|
|
468
|
-
};
|
|
469
|
-
});
|
|
470
|
-
|
|
471
|
-
payload.eModeCategory = +(eModeCategory as BigInt).toString();
|
|
472
|
-
payload = {
|
|
473
|
-
...payload,
|
|
474
|
-
usedAssets,
|
|
475
|
-
...aaveAnyGetAggregatedPositionData({
|
|
476
|
-
...extractedState, usedAssets, eModeCategory: payload.eModeCategory,
|
|
477
|
-
}),
|
|
478
|
-
};
|
|
479
|
-
payload.eModeCategories = aaveV3EmodeCategoriesMapping(extractedState, usedAssets);
|
|
480
|
-
payload.isInIsolationMode = aaveV3IsInIsolationMode({ usedAssets, assetsData });
|
|
481
|
-
payload.isInSiloedMode = aaveV3IsInSiloedMode({ usedAssets, assetsData });
|
|
482
|
-
|
|
483
|
-
payload.ratio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
484
|
-
? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
485
|
-
: '0';
|
|
486
|
-
payload.minRatio = '100';
|
|
487
|
-
payload.collRatio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
488
|
-
? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
489
|
-
: '0';
|
|
490
|
-
|
|
491
|
-
// Calculate borrow limits per asset
|
|
492
|
-
Object.values(payload.usedAssets).forEach((item) => {
|
|
493
|
-
if (item.isBorrowed) {
|
|
494
|
-
// eslint-disable-next-line no-param-reassign
|
|
495
|
-
item.stableLimit = calculateBorrowingAssetLimit(item.borrowedUsdStable, payload.borrowLimitUsd);
|
|
496
|
-
// eslint-disable-next-line no-param-reassign
|
|
497
|
-
item.variableLimit = calculateBorrowingAssetLimit(item.borrowedUsdVariable, payload.borrowLimitUsd);
|
|
498
|
-
// eslint-disable-next-line no-param-reassign
|
|
499
|
-
item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
|
|
500
|
-
}
|
|
501
|
-
});
|
|
502
|
-
|
|
503
|
-
payload.isSubscribedToAutomation = false;
|
|
504
|
-
payload.automationResubscribeRequired = false;
|
|
505
|
-
|
|
506
|
-
return payload;
|
|
507
|
-
};
|
|
508
|
-
|
|
509
|
-
export const getAaveV3AccountData = async (provider: EthereumProvider, network: NetworkNumber, address: EthAddress, extractedState: any, blockNumber: 'latest' | number = 'latest'): Promise<AaveV3PositionData> => _getAaveV3AccountData(getViemProvider(provider, network), network, address, extractedState, blockNumber);
|
|
510
|
-
|
|
511
|
-
export const getAaveV3FullPositionData = async (provider: EthereumProvider, network: NetworkNumber, address: EthAddress, market: AaveMarketInfo): Promise<AaveV3PositionData> => {
|
|
512
|
-
const marketData = await getAaveV3MarketData(provider, network, market);
|
|
513
|
-
const positionData = await getAaveV3AccountData(provider, network, address, { assetsData: marketData.assetsData, selectedMarket: market, eModeCategoriesData: marketData.eModeCategoriesData });
|
|
514
|
-
return positionData;
|
|
515
|
-
};
|
|
516
|
-
|
|
517
|
-
// aTokens eligible for AAVE rewards
|
|
518
|
-
export const REWARDABLE_ASSETS = [
|
|
519
|
-
'0x028171bCA77440897B824Ca71D1c56caC55b68A3', // DAI
|
|
520
|
-
'0x6C3c78838c761c6Ac7bE9F59fe808ea2A6E4379d',
|
|
521
|
-
'0xD37EE7e4f452C6638c96536e68090De8cBcdb583', // GUSD
|
|
522
|
-
'0x279AF5b99540c1A3A7E3CDd326e19659401eF99e',
|
|
523
|
-
'0xBcca60bB61934080951369a648Fb03DF4F96263C', // USDC
|
|
524
|
-
'0x619beb58998eD2278e08620f97007e1116D5D25b',
|
|
525
|
-
'0x3Ed3B47Dd13EC9a98b44e6204A523E766B225811', // USDT
|
|
526
|
-
'0x531842cEbbdD378f8ee36D171d6cC9C4fcf475Ec',
|
|
527
|
-
'0x9ff58f4fFB29fA2266Ab25e75e2A8b3503311656', // WBTC
|
|
528
|
-
'0x9c39809Dec7F95F5e0713634a4D0701329B3b4d2',
|
|
529
|
-
'0x030bA81f1c18d280636F32af80b9AAd02Cf0854e', // WETH
|
|
530
|
-
'0xF63B34710400CAd3e044cFfDcAb00a0f32E33eCf',
|
|
531
|
-
'0xa06bC25B5805d5F8d82847D191Cb4Af5A3e873E0', // LINK
|
|
532
|
-
'0x0b8f12b1788BFdE65Aa1ca52E3e9F3Ba401be16D',
|
|
533
|
-
'0x6C5024Cd4F8A59110119C56f8933403A539555EB', // SUSD
|
|
534
|
-
'0xdC6a3Ab17299D9C2A412B0e0a4C1f55446AE0817',
|
|
535
|
-
'0x5165d24277cD063F5ac44Efd447B27025e888f37', // YFI
|
|
536
|
-
'0x7EbD09022Be45AD993BAA1CEc61166Fcc8644d97',
|
|
537
|
-
'0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a', // xSUSHI
|
|
538
|
-
'0xfAFEDF95E21184E3d880bd56D4806c4b8d31c69A',
|
|
539
|
-
'0xB9D7CB55f463405CDfBe4E90a6D2Df01C2B92BF1', // UNI
|
|
540
|
-
'0x5BdB050A92CADcCfCDcCCBFC17204a1C9cC0Ab73',
|
|
541
|
-
'0xc713e5E149D5D0715DcD1c156a020976e7E56B88', // MKR
|
|
542
|
-
'0xba728eAd5e496BE00DCF66F650b6d7758eCB50f8',
|
|
543
|
-
'0x101cc05f4A51C0319f570d5E146a8C625198e636', // TUSD
|
|
544
|
-
'0x01C0eb1f8c6F1C1bF74ae028697ce7AA2a8b0E92',
|
|
545
|
-
'0xc9BC48c72154ef3e5425641a3c747242112a46AF', // RAI
|
|
546
|
-
'0xB5385132EE8321977FfF44b60cDE9fE9AB0B4e6b',
|
|
547
|
-
'0x272F97b7a56a387aE942350bBC7Df5700f8a4576', // BAL
|
|
548
|
-
'0x13210D4Fe0d5402bd7Ecbc4B5bC5cFcA3b71adB0',
|
|
549
|
-
'0x2e8f4bdbe3d47d7d7de490437aea9915d930f1a3', // USDP
|
|
550
|
-
'0xfdb93b3b10936cf81fa59a02a7523b6e2149b2b7',
|
|
551
|
-
'0xA361718326c15715591c299427c62086F69923D9', // BUSD
|
|
552
|
-
'0xbA429f7011c9fa04cDd46a2Da24dc0FF0aC6099c',
|
|
553
|
-
'0xd4937682df3C8aEF4FE912A96A74121C0829E664', // FRAX
|
|
554
|
-
'0xfE8F19B17fFeF0fDbfe2671F248903055AFAA8Ca',
|
|
555
|
-
'0x683923dB55Fead99A79Fa01A27EeC3cB19679cC3', // FEI
|
|
556
|
-
'0xC2e10006AccAb7B45D9184FcF5b7EC7763f5BaAe',
|
|
557
|
-
'0x8dAE6Cb04688C62d939ed9B68d32Bc62e49970b1', // CRV
|
|
558
|
-
'0x00ad8eBF64F141f1C81e9f8f792d3d1631c6c684',
|
|
559
|
-
'0x6F634c6135D2EBD550000ac92F494F9CB8183dAe', // DPI
|
|
560
|
-
'0x4dDff5885a67E4EffeC55875a3977D7E60F82ae0',
|
|
561
|
-
] as const;
|
|
562
|
-
|
|
563
|
-
export const fetchYearlyMeritApyForStakingGho = async () => {
|
|
564
|
-
try {
|
|
565
|
-
const response = await fetch('https://apps.aavechan.com/api/merit/aprs', { signal: AbortSignal.timeout(5000) });
|
|
566
|
-
const data = await response.json();
|
|
567
|
-
const apr = data?.currentAPR?.actionsAPR?.['ethereum-stkgho'] || '0' as string;
|
|
568
|
-
const apy = aprToApy(apr);
|
|
569
|
-
const apyWithDFSBonus = new Dec(apy).mul(1.05).toString(); // 5% bonus for DFS users
|
|
570
|
-
return apyWithDFSBonus;
|
|
571
|
-
} catch (e) {
|
|
572
|
-
const message = 'External API Failure: Failed to fetch yearly merit APY for staking GHO';
|
|
573
|
-
console.error(message, e);
|
|
574
|
-
return '0';
|
|
575
|
-
}
|
|
576
|
-
};
|
|
577
|
-
|
|
578
|
-
export const getStakeAaveData = async (provider: Client, network: NetworkNumber, address: EthAddress) => {
|
|
579
|
-
const stkGhoAddress = getAssetInfo('stkGHO').address as HexString;
|
|
580
|
-
const stkAaveAddress = getAssetInfo('stkAAVE').address as HexString;
|
|
581
|
-
|
|
582
|
-
const AaveIncentivesController = AaveIncentivesControllerViem(provider, network);
|
|
583
|
-
const stkAAVE = StkAAVEViem(provider, network);
|
|
584
|
-
const stkGHO = createViemContractFromConfigFunc('Erc20', stkGhoAddress as HexString)(provider, network);
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
const [aaveRewardsBalance, emissionsPerSecond, stkAAVEBalance, stkAAVETotalSupply, stkGHOBalance, ghoMeritApy] = await Promise.all([
|
|
588
|
-
AaveIncentivesController.read.getRewardsBalance([REWARDABLE_ASSETS, address]),
|
|
589
|
-
stkAAVE.read.assets([stkAaveAddress]),
|
|
590
|
-
stkAAVE.read.balanceOf([address]),
|
|
591
|
-
stkAAVE.read.totalSupply(),
|
|
592
|
-
stkGHO.read.balanceOf([address]),
|
|
593
|
-
fetchYearlyMeritApyForStakingGho(),
|
|
594
|
-
]);
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
const stkAaveApy = new Dec(assetAmountInEth(emissionsPerSecond[0].toString(), 'GHO') || 0).mul(SECONDS_PER_YEAR).mul(100).div(assetAmountInEth(stkAAVETotalSupply.toString(), 'stkAAVE'))
|
|
598
|
-
.toString();
|
|
599
|
-
return {
|
|
600
|
-
activatedCooldown: '0',
|
|
601
|
-
activatedCooldownAmount: '0',
|
|
602
|
-
stkAaveRewardsBalance: '0',
|
|
603
|
-
aaveRewardsBalance: assetAmountInEth(aaveRewardsBalance.toString(), 'AAVE'),
|
|
604
|
-
stkAaveBalance: assetAmountInEth(stkAAVEBalance.toString(), 'stkAAVE'),
|
|
605
|
-
stkGhoBalance: assetAmountInEth(stkGHOBalance.toString(), 'GHO'),
|
|
606
|
-
ghoMeritApy,
|
|
607
|
-
stkAaveApy,
|
|
608
|
-
};
|
|
609
|
-
};
|
|
610
|
-
|
|
611
|
-
export {
|
|
612
|
-
getMeritCampaigns,
|
|
613
|
-
getMerkleCampaigns,
|
|
614
|
-
};
|
|
1
|
+
import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
|
|
2
|
+
import { Client } from 'viem';
|
|
3
|
+
import Dec from 'decimal.js';
|
|
4
|
+
import {
|
|
5
|
+
AaveIncentiveDataProviderV3ContractViem,
|
|
6
|
+
AaveIncentivesControllerViem,
|
|
7
|
+
AaveV3ViewContractViem,
|
|
8
|
+
createViemContractFromConfigFunc,
|
|
9
|
+
StkAAVEViem,
|
|
10
|
+
} from '../contracts';
|
|
11
|
+
import { aaveAnyGetAggregatedPositionData, aaveV3IsInIsolationMode, aaveV3IsInSiloedMode } from '../helpers/aaveHelpers';
|
|
12
|
+
import { AAVE_V3 } from '../markets/aave';
|
|
13
|
+
import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
|
|
14
|
+
import {
|
|
15
|
+
getWrappedNativeAssetFromUnwrapped, isEnabledOnBitmap, isLayer2Network, wethToEth, wethToEthByAddress,
|
|
16
|
+
} from '../services/utils';
|
|
17
|
+
import { getStakingApy, STAKING_ASSETS } from '../staking';
|
|
18
|
+
import {
|
|
19
|
+
AaveMarketInfo,
|
|
20
|
+
AaveV3AssetData,
|
|
21
|
+
AaveV3AssetsData,
|
|
22
|
+
AaveV3MarketData,
|
|
23
|
+
AaveV3PositionData,
|
|
24
|
+
AaveV3UsedAsset,
|
|
25
|
+
AaveV3UsedAssets,
|
|
26
|
+
EModeCategoriesData,
|
|
27
|
+
EModeCategoryData,
|
|
28
|
+
EModeCategoryDataMapping,
|
|
29
|
+
} from '../types/aave';
|
|
30
|
+
import {
|
|
31
|
+
Blockish, EthAddress, EthereumProvider, IncentiveEligibilityId, IncentiveKind, NetworkNumber, PositionBalances, HexString,
|
|
32
|
+
} from '../types/common';
|
|
33
|
+
import { getViemProvider, setViemBlockNumber } from '../services/viem';
|
|
34
|
+
import { getMeritCampaigns } from './merit';
|
|
35
|
+
import { getAaveUnderlyingSymbol, getMerkleCampaigns } from './merkl';
|
|
36
|
+
import { SECONDS_PER_DAY, SECONDS_PER_YEAR } from '../constants';
|
|
37
|
+
|
|
38
|
+
export const aaveV3EmodeCategoriesMapping = (extractedState: any, usedAssets: AaveV3UsedAssets) => {
|
|
39
|
+
const { eModeCategoriesData }: { assetsData: AaveV3AssetsData, eModeCategoriesData: EModeCategoriesData } = extractedState;
|
|
40
|
+
const usedAssetsValues = Object.values(usedAssets);
|
|
41
|
+
|
|
42
|
+
const categoriesMapping: { [key: number]: EModeCategoryDataMapping } = {};
|
|
43
|
+
|
|
44
|
+
Object.values(eModeCategoriesData).forEach((e: EModeCategoryData) => {
|
|
45
|
+
const borrowingOnlyFromCategory = e.id === 0
|
|
46
|
+
? true
|
|
47
|
+
: !usedAssetsValues.filter(u => u.isBorrowed && !e.borrowAssets.includes(u.symbol)).length;
|
|
48
|
+
const afterEnteringCategory = aaveAnyGetAggregatedPositionData({
|
|
49
|
+
...extractedState, usedAssets, eModeCategory: e.id,
|
|
50
|
+
});
|
|
51
|
+
const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent);
|
|
52
|
+
const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized];
|
|
53
|
+
categoriesMapping[e.id] = {
|
|
54
|
+
enteringTerms,
|
|
55
|
+
canEnterCategory: !enteringTerms.includes(false),
|
|
56
|
+
id: e.id,
|
|
57
|
+
enabledData: {
|
|
58
|
+
ratio: afterEnteringCategory.ratio,
|
|
59
|
+
liqRatio: afterEnteringCategory.liqRatio,
|
|
60
|
+
liqPercent: afterEnteringCategory.liqPercent,
|
|
61
|
+
collRatio: afterEnteringCategory.collRatio,
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
return categoriesMapping;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export async function _getAaveV3MarketData(provider: Client, network: NetworkNumber, market: AaveMarketInfo, blockNumber: 'latest' | number = 'latest'): Promise<AaveV3MarketData> {
|
|
69
|
+
const _addresses = market.assets.map(a => getAssetInfo(getWrappedNativeAssetFromUnwrapped(a), network).address);
|
|
70
|
+
|
|
71
|
+
const isL2 = isLayer2Network(network);
|
|
72
|
+
const loanInfoContract = AaveV3ViewContractViem(provider, network);
|
|
73
|
+
const aaveIncentivesContract = AaveIncentiveDataProviderV3ContractViem(provider, network);
|
|
74
|
+
const marketAddress = market.providerAddress;
|
|
75
|
+
const networksWithIncentives = [NetworkNumber.Eth, NetworkNumber.Arb, NetworkNumber.Opt, NetworkNumber.Linea, NetworkNumber.Plasma];
|
|
76
|
+
|
|
77
|
+
// eslint-disable-next-line prefer-const
|
|
78
|
+
let [loanInfo, eModesInfo, isBorrowAllowed, rewardInfo, merkleRewardsMap, meritRewardsMap] = await Promise.all([
|
|
79
|
+
loanInfoContract.read.getFullTokensInfo([marketAddress, _addresses as EthAddress[]], setViemBlockNumber(blockNumber)),
|
|
80
|
+
loanInfoContract.read.getAllEmodes([marketAddress], setViemBlockNumber(blockNumber)),
|
|
81
|
+
loanInfoContract.read.isBorrowAllowed([marketAddress], setViemBlockNumber(blockNumber)), // Used on L2s check for PriceOracleSentinel (mainnet will always return true)
|
|
82
|
+
networksWithIncentives.includes(network) ? aaveIncentivesContract.read.getReservesIncentivesData([marketAddress], setViemBlockNumber(blockNumber)) : null,
|
|
83
|
+
getMerkleCampaigns(network),
|
|
84
|
+
getMeritCampaigns(network, market.value),
|
|
85
|
+
]);
|
|
86
|
+
isBorrowAllowed = isLayer2Network(network) ? isBorrowAllowed : true;
|
|
87
|
+
|
|
88
|
+
const eModeCategoriesData: EModeCategoriesData = {};
|
|
89
|
+
for (let i = 0; i < eModesInfo.length; i++) {
|
|
90
|
+
if (!eModesInfo[i].label) break;
|
|
91
|
+
eModeCategoriesData[i + 1] = {
|
|
92
|
+
label: eModesInfo[i].label,
|
|
93
|
+
id: i + 1,
|
|
94
|
+
liquidationBonus: new Dec(eModesInfo[i].liquidationBonus).div(10000).toString(),
|
|
95
|
+
liquidationRatio: new Dec(eModesInfo[i].liquidationThreshold).div(10000).toString(),
|
|
96
|
+
collateralFactor: new Dec(eModesInfo[i].ltv).div(10000).toString(),
|
|
97
|
+
borrowableBitmap: eModesInfo[i].borrowableBitmap.toString(),
|
|
98
|
+
collateralBitmap: eModesInfo[i].collateralBitmap.toString(),
|
|
99
|
+
borrowAssets: [],
|
|
100
|
+
collateralAssets: [],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (networksWithIncentives.includes(network) && rewardInfo) {
|
|
105
|
+
rewardInfo = rewardInfo.reduce((all: any, _market: any) => {
|
|
106
|
+
// eslint-disable-next-line no-param-reassign
|
|
107
|
+
all[_market.underlyingAsset] = _market;
|
|
108
|
+
return all;
|
|
109
|
+
}, {});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const assetsData: AaveV3AssetData[] = await Promise.all(loanInfo
|
|
113
|
+
.map(async (tokenMarket, i) => {
|
|
114
|
+
const symbol = market.assets[i];
|
|
115
|
+
|
|
116
|
+
// eslint-disable-next-line guard-for-in
|
|
117
|
+
for (const eModeIndex in eModeCategoriesData) {
|
|
118
|
+
if (isEnabledOnBitmap(Number(eModeCategoriesData[eModeIndex].collateralBitmap), Number(tokenMarket.assetId))) eModeCategoriesData[eModeIndex].collateralAssets.push(symbol);
|
|
119
|
+
if (isEnabledOnBitmap(Number(eModeCategoriesData[eModeIndex].borrowableBitmap), Number(tokenMarket.assetId))) eModeCategoriesData[eModeIndex].borrowAssets.push(symbol);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const borrowCap = tokenMarket.borrowCap.toString();
|
|
123
|
+
|
|
124
|
+
const borrowCapInWei = new Dec(assetAmountInWei(borrowCap, symbol));
|
|
125
|
+
let marketLiquidity = borrowCapInWei.lt(new Dec(tokenMarket.totalSupply.toString()))
|
|
126
|
+
? assetAmountInEth(borrowCapInWei
|
|
127
|
+
.sub(tokenMarket.totalBorrow.toString())
|
|
128
|
+
.toString(), symbol)
|
|
129
|
+
: assetAmountInEth(new Dec(tokenMarket.totalSupply.toString())
|
|
130
|
+
.sub(tokenMarket.totalBorrow.toString())
|
|
131
|
+
.toString(), symbol);
|
|
132
|
+
|
|
133
|
+
if (new Dec(marketLiquidity).lt(0)) {
|
|
134
|
+
marketLiquidity = '0';
|
|
135
|
+
}
|
|
136
|
+
return ({
|
|
137
|
+
symbol,
|
|
138
|
+
isIsolated: new Dec(tokenMarket.debtCeilingForIsolationMode.toString()).gt(0),
|
|
139
|
+
debtCeilingForIsolationMode: new Dec(tokenMarket.debtCeilingForIsolationMode.toString()).div(100).toString(),
|
|
140
|
+
isSiloed: tokenMarket.isSiloedForBorrowing,
|
|
141
|
+
isolationModeTotalDebt: new Dec(tokenMarket.isolationModeTotalDebt.toString()).div(100).toString(),
|
|
142
|
+
assetId: Number(tokenMarket.assetId),
|
|
143
|
+
underlyingTokenAddress: tokenMarket.underlyingTokenAddress,
|
|
144
|
+
supplyRate: aprToApy(new Dec(tokenMarket.supplyRate.toString()).div(1e25).toString()),
|
|
145
|
+
borrowRate: aprToApy(new Dec(tokenMarket.borrowRateVariable.toString()).div(1e25).toString()),
|
|
146
|
+
borrowRateStable: aprToApy(new Dec(tokenMarket.borrowRateStable.toString()).div(1e25).toString()),
|
|
147
|
+
collateralFactor: new Dec(tokenMarket.collateralFactor.toString()).div(10000).toString(),
|
|
148
|
+
liquidationBonus: new Dec(tokenMarket.liquidationBonus.toString()).div(10000).toString(),
|
|
149
|
+
liquidationRatio: new Dec(tokenMarket.liquidationRatio.toString()).div(10000).toString(),
|
|
150
|
+
marketLiquidity,
|
|
151
|
+
utilization: new Dec(tokenMarket.totalBorrow.toString()).times(100).div(new Dec(tokenMarket.totalSupply.toString())).toString(),
|
|
152
|
+
usageAsCollateralEnabled: tokenMarket.usageAsCollateralEnabled,
|
|
153
|
+
supplyCap: tokenMarket.supplyCap.toString(),
|
|
154
|
+
borrowCap,
|
|
155
|
+
totalSupply: assetAmountInEth(tokenMarket.totalSupply.toString(), symbol),
|
|
156
|
+
isInactive: !tokenMarket.isActive,
|
|
157
|
+
isFrozen: tokenMarket.isFrozen,
|
|
158
|
+
isPaused: tokenMarket.isPaused,
|
|
159
|
+
canBeBorrowed: tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen && tokenMarket.borrowingEnabled && isBorrowAllowed,
|
|
160
|
+
canBeSupplied: tokenMarket.isActive && !tokenMarket.isPaused && !tokenMarket.isFrozen,
|
|
161
|
+
canBeWithdrawn: tokenMarket.isActive && !tokenMarket.isPaused,
|
|
162
|
+
canBePayBacked: tokenMarket.isActive && !tokenMarket.isPaused,
|
|
163
|
+
disabledStableBorrowing: !tokenMarket.stableBorrowRateEnabled,
|
|
164
|
+
totalBorrow: assetAmountInEth(tokenMarket.totalBorrow.toString(), symbol),
|
|
165
|
+
totalBorrowVar: assetAmountInEth(tokenMarket.totalBorrowVar.toString(), symbol),
|
|
166
|
+
price: new Dec(tokenMarket.price.toString()).div(1e8).toString(), // is actually price in USD
|
|
167
|
+
isolationModeBorrowingEnabled: tokenMarket.isolationModeBorrowingEnabled,
|
|
168
|
+
isFlashLoanEnabled: tokenMarket.isFlashLoanEnabled,
|
|
169
|
+
aTokenAddress: tokenMarket.aTokenAddress,
|
|
170
|
+
vTokenAddress: tokenMarket.debtTokenAddress,
|
|
171
|
+
supplyIncentives: [],
|
|
172
|
+
borrowIncentives: [],
|
|
173
|
+
});
|
|
174
|
+
}),
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
// Get incentives data
|
|
178
|
+
await Promise.all(assetsData.map(async (_market: AaveV3AssetData, index) => {
|
|
179
|
+
/* eslint-disable no-param-reassign */
|
|
180
|
+
// @ts-ignore
|
|
181
|
+
const rewardForMarket = rewardInfo?.[_market.underlyingTokenAddress];
|
|
182
|
+
const isStakingAsset = STAKING_ASSETS.includes(_market.symbol);
|
|
183
|
+
|
|
184
|
+
if (isStakingAsset) {
|
|
185
|
+
const yieldApy = await getStakingApy(_market.symbol, network as NetworkNumber);
|
|
186
|
+
_market.supplyIncentives.push({
|
|
187
|
+
apy: yieldApy,
|
|
188
|
+
token: _market.symbol,
|
|
189
|
+
incentiveKind: IncentiveKind.Staking,
|
|
190
|
+
description: `Native ${_market.symbol} yield.`,
|
|
191
|
+
});
|
|
192
|
+
if (_market.canBeBorrowed) {
|
|
193
|
+
// when borrowing assets whose value increases over time
|
|
194
|
+
_market.borrowIncentives.push({
|
|
195
|
+
apy: new Dec(yieldApy).mul(-1).toString(),
|
|
196
|
+
token: _market.symbol,
|
|
197
|
+
incentiveKind: IncentiveKind.Reward,
|
|
198
|
+
description: `Due to the native yield of ${_market.symbol}, the value of the debt would increase over time.`,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const aTokenAddress = (_market as any).aTokenAddress.toLowerCase(); // DEV: Should aTokenAddress be in AaveV3AssetData type?
|
|
204
|
+
if (merkleRewardsMap[aTokenAddress]?.supply) {
|
|
205
|
+
const {
|
|
206
|
+
apy, rewardTokenSymbol, description, identifier,
|
|
207
|
+
} = merkleRewardsMap[aTokenAddress].supply;
|
|
208
|
+
_market.supplyIncentives.push({
|
|
209
|
+
apy,
|
|
210
|
+
token: rewardTokenSymbol,
|
|
211
|
+
incentiveKind: IncentiveKind.Reward,
|
|
212
|
+
description,
|
|
213
|
+
eligibilityId: identifier as IncentiveEligibilityId,
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const vTokenAddress = (_market as any).vTokenAddress.toLowerCase(); // DEV: Should vTokenAddress be in AaveV3AssetData type?
|
|
218
|
+
if (merkleRewardsMap[vTokenAddress]?.borrow) {
|
|
219
|
+
const {
|
|
220
|
+
apy, rewardTokenSymbol, description, identifier,
|
|
221
|
+
} = merkleRewardsMap[vTokenAddress].borrow;
|
|
222
|
+
_market.borrowIncentives.push({
|
|
223
|
+
apy,
|
|
224
|
+
token: rewardTokenSymbol,
|
|
225
|
+
incentiveKind: IncentiveKind.Reward,
|
|
226
|
+
description,
|
|
227
|
+
eligibilityId: identifier as IncentiveEligibilityId,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (meritRewardsMap.supply[_market.symbol]) {
|
|
232
|
+
const { apy, rewardTokenSymbol, description } = meritRewardsMap.supply[_market.symbol];
|
|
233
|
+
_market.supplyIncentives.push({
|
|
234
|
+
apy,
|
|
235
|
+
token: rewardTokenSymbol,
|
|
236
|
+
incentiveKind: IncentiveKind.Reward,
|
|
237
|
+
description,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (meritRewardsMap.borrow[_market.symbol]) {
|
|
242
|
+
const { apy, rewardTokenSymbol, description } = meritRewardsMap.borrow[_market.symbol];
|
|
243
|
+
_market.borrowIncentives.push({
|
|
244
|
+
apy,
|
|
245
|
+
token: rewardTokenSymbol,
|
|
246
|
+
incentiveKind: IncentiveKind.Reward,
|
|
247
|
+
description,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (!rewardForMarket) return;
|
|
252
|
+
// @ts-ignore
|
|
253
|
+
rewardForMarket.aIncentiveData.rewardsTokenInformation.forEach(supplyRewardData => {
|
|
254
|
+
if (supplyRewardData) {
|
|
255
|
+
if (+(supplyRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return;
|
|
256
|
+
// reward token is aave asset
|
|
257
|
+
const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond;
|
|
258
|
+
const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** +supplyRewardData.priceFeedDecimals)
|
|
259
|
+
.toString();
|
|
260
|
+
const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** +supplyRewardData.rewardTokenDecimals) / 100)
|
|
261
|
+
.mul(365 * 24 * 3600)
|
|
262
|
+
.mul(supplyRewardPrice)
|
|
263
|
+
.div(_market.price)
|
|
264
|
+
.div(_market.totalSupply)
|
|
265
|
+
.toString();
|
|
266
|
+
_market.supplyIncentives.push({
|
|
267
|
+
token: getAaveUnderlyingSymbol(supplyRewardData.rewardTokenSymbol),
|
|
268
|
+
apy: rewardApy,
|
|
269
|
+
incentiveKind: IncentiveKind.Reward,
|
|
270
|
+
description: 'Eligible for protocol-level incentives.',
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
// @ts-ignore
|
|
275
|
+
rewardForMarket.vIncentiveData.rewardsTokenInformation.forEach(borrowRewardData => {
|
|
276
|
+
if (borrowRewardData) {
|
|
277
|
+
if (+(borrowRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return;
|
|
278
|
+
const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond;
|
|
279
|
+
const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** +borrowRewardData.priceFeedDecimals)
|
|
280
|
+
.toString();
|
|
281
|
+
const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** +borrowRewardData.rewardTokenDecimals) / 100)
|
|
282
|
+
.mul(365 * 24 * 3600)
|
|
283
|
+
.mul(supplyRewardPrice)
|
|
284
|
+
.div(_market.price)
|
|
285
|
+
.div(_market.totalBorrowVar)
|
|
286
|
+
.toString();
|
|
287
|
+
_market.borrowIncentives.push({
|
|
288
|
+
token: getAaveUnderlyingSymbol(borrowRewardData.rewardTokenSymbol),
|
|
289
|
+
apy: rewardApy,
|
|
290
|
+
incentiveKind: IncentiveKind.Reward,
|
|
291
|
+
description: 'Eligible for protocol-level incentives.',
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
}));
|
|
296
|
+
|
|
297
|
+
const payload: AaveV3AssetsData = {};
|
|
298
|
+
// Sort by market size
|
|
299
|
+
assetsData
|
|
300
|
+
.sort((a, b) => {
|
|
301
|
+
const aMarket = new Dec(a.price).times(a.totalSupply).toString();
|
|
302
|
+
const bMarket = new Dec(b.price).times(b.totalSupply).toString();
|
|
303
|
+
|
|
304
|
+
return new Dec(bMarket).minus(aMarket).toNumber();
|
|
305
|
+
})
|
|
306
|
+
.forEach((assetData: AaveV3AssetData, i) => {
|
|
307
|
+
payload[assetData.symbol] = { ...assetData, sortIndex: i };
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
eModeCategoriesData[0] = {
|
|
311
|
+
id: 0,
|
|
312
|
+
label: '',
|
|
313
|
+
liquidationBonus: '0',
|
|
314
|
+
liquidationRatio: '0',
|
|
315
|
+
collateralFactor: '0',
|
|
316
|
+
collateralAssets: assetsData.map((a) => a.symbol),
|
|
317
|
+
borrowAssets: assetsData.map((a) => a.symbol),
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
return { assetsData: payload, eModeCategoriesData };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export async function getAaveV3MarketData(provider: EthereumProvider, network: NetworkNumber, market: AaveMarketInfo, blockNumber: 'latest' | number = 'latest'): Promise<AaveV3MarketData> {
|
|
324
|
+
return _getAaveV3MarketData(getViemProvider(provider, network), network, market, blockNumber);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export const EMPTY_AAVE_DATA = {
|
|
328
|
+
usedAssets: {},
|
|
329
|
+
suppliedUsd: '0',
|
|
330
|
+
borrowedUsd: '0',
|
|
331
|
+
borrowLimitUsd: '0',
|
|
332
|
+
leftToBorrowUsd: '0',
|
|
333
|
+
ratio: '0',
|
|
334
|
+
minRatio: '0',
|
|
335
|
+
netApy: '0',
|
|
336
|
+
incentiveUsd: '0',
|
|
337
|
+
totalInterestUsd: '0',
|
|
338
|
+
isSubscribedToAutomation: false,
|
|
339
|
+
automationResubscribeRequired: false,
|
|
340
|
+
eModeCategory: 0,
|
|
341
|
+
isInIsolationMode: false,
|
|
342
|
+
isInSiloedMode: false,
|
|
343
|
+
totalSupplied: '0',
|
|
344
|
+
eModeCategories: [],
|
|
345
|
+
collRatio: '0',
|
|
346
|
+
suppliedCollateralUsd: '0',
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
export const _getAaveV3AccountBalances = async (provider: Client, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
|
|
350
|
+
let balances: PositionBalances = {
|
|
351
|
+
collateral: {},
|
|
352
|
+
debt: {},
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
if (!address) {
|
|
356
|
+
return balances;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const loanInfoContract = AaveV3ViewContractViem(provider, network, block);
|
|
360
|
+
|
|
361
|
+
const market = AAVE_V3(network);
|
|
362
|
+
const marketAddress = market.providerAddress;
|
|
363
|
+
// @ts-ignore
|
|
364
|
+
const protocolDataProviderContract = createViemContractFromConfigFunc(market.protocolData, market.protocolDataAddress)(provider, network);
|
|
365
|
+
|
|
366
|
+
// @ts-ignore
|
|
367
|
+
const reserveTokens = await protocolDataProviderContract.read.getAllReservesTokens(setViemBlockNumber(block)) as { symbol: string, tokenAddress: EthAddress }[];
|
|
368
|
+
const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
|
|
369
|
+
const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
|
|
370
|
+
|
|
371
|
+
// split addresses in half to avoid gas limit by multicall
|
|
372
|
+
const middleAddressIndex = Math.floor(_addresses.length / 2);
|
|
373
|
+
|
|
374
|
+
const [tokenBalances1, tokenBalances2] = await Promise.all([
|
|
375
|
+
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex)], setViemBlockNumber(block)),
|
|
376
|
+
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)], setViemBlockNumber(block)),
|
|
377
|
+
]);
|
|
378
|
+
|
|
379
|
+
const loanInfo = [...tokenBalances1, ...tokenBalances2];
|
|
380
|
+
|
|
381
|
+
loanInfo.forEach((tokenInfo: any, i: number) => {
|
|
382
|
+
const asset = wethToEth(symbols[i]);
|
|
383
|
+
const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
|
|
384
|
+
|
|
385
|
+
balances = {
|
|
386
|
+
collateral: {
|
|
387
|
+
...balances.collateral,
|
|
388
|
+
[addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
|
|
389
|
+
},
|
|
390
|
+
debt: {
|
|
391
|
+
...balances.debt,
|
|
392
|
+
[addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
return balances;
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
export const getAaveV3AccountBalances = async (provider: EthereumProvider, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => _getAaveV3AccountBalances(getViemProvider(provider, network), network, block, addressMapping, address);
|
|
401
|
+
|
|
402
|
+
export const _getAaveV3AccountData = async (provider: Client, network: NetworkNumber, address: EthAddress, extractedState: any, blockNumber: 'latest' | number = 'latest'): Promise<AaveV3PositionData> => {
|
|
403
|
+
const {
|
|
404
|
+
selectedMarket: market, assetsData,
|
|
405
|
+
} = extractedState;
|
|
406
|
+
let payload: AaveV3PositionData = {
|
|
407
|
+
...EMPTY_AAVE_DATA,
|
|
408
|
+
lastUpdated: Date.now(),
|
|
409
|
+
};
|
|
410
|
+
if (!address) {
|
|
411
|
+
return payload;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const loanInfoContract = AaveV3ViewContractViem(provider, network);
|
|
415
|
+
const lendingPoolContract = createViemContractFromConfigFunc(market.lendingPool, market.lendingPoolAddress)(provider, network);
|
|
416
|
+
const marketAddress = market.providerAddress;
|
|
417
|
+
const _addresses = market.assets.map((a: string) => getAssetInfo(getWrappedNativeAssetFromUnwrapped(a), network).address);
|
|
418
|
+
|
|
419
|
+
const middleAddressIndex = Math.floor(_addresses.length / 2); // split addresses in half to avoid gas limit by multicall
|
|
420
|
+
|
|
421
|
+
const [eModeCategory, tokenBalances1, tokenBalances2] = await Promise.all([
|
|
422
|
+
lendingPoolContract.read.getUserEMode([address], setViemBlockNumber(blockNumber)),
|
|
423
|
+
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex) as EthAddress[]], setViemBlockNumber(blockNumber)),
|
|
424
|
+
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length) as EthAddress[]], setViemBlockNumber(blockNumber)),
|
|
425
|
+
]);
|
|
426
|
+
|
|
427
|
+
const loanInfo = [...tokenBalances1, ...tokenBalances2];
|
|
428
|
+
|
|
429
|
+
const usedAssets = {} as AaveV3UsedAssets;
|
|
430
|
+
loanInfo.map(async (tokenInfo, i) => {
|
|
431
|
+
const asset = market.assets[i];
|
|
432
|
+
const isSupplied = tokenInfo.balance.toString() !== '0';
|
|
433
|
+
const isBorrowed = tokenInfo.borrowsStable.toString() !== '0' || tokenInfo.borrowsVariable.toString() !== '0';
|
|
434
|
+
if (!isSupplied && !isBorrowed) return;
|
|
435
|
+
|
|
436
|
+
const supplied = assetAmountInEth(tokenInfo.balance.toString(), asset);
|
|
437
|
+
const borrowedStable = assetAmountInEth(tokenInfo.borrowsStable.toString(), asset);
|
|
438
|
+
const borrowedVariable = assetAmountInEth(tokenInfo.borrowsVariable.toString(), asset);
|
|
439
|
+
const enabledAsCollateral = assetsData[asset].usageAsCollateralEnabled ? tokenInfo.enabledAsCollateral : false;
|
|
440
|
+
|
|
441
|
+
let interestMode;
|
|
442
|
+
if (borrowedVariable === '0' && borrowedStable !== '0') {
|
|
443
|
+
interestMode = '1';
|
|
444
|
+
} else if (borrowedVariable !== '0' && borrowedStable === '0') {
|
|
445
|
+
interestMode = '2';
|
|
446
|
+
} else {
|
|
447
|
+
interestMode = 'both';
|
|
448
|
+
}
|
|
449
|
+
if (!usedAssets[asset]) usedAssets[asset] = {} as AaveV3UsedAsset;
|
|
450
|
+
const borrowed = new Dec(borrowedStable).add(borrowedVariable).toString();
|
|
451
|
+
|
|
452
|
+
usedAssets[asset] = {
|
|
453
|
+
...usedAssets[asset],
|
|
454
|
+
symbol: asset,
|
|
455
|
+
supplied,
|
|
456
|
+
suppliedUsd: new Dec(supplied).mul(assetsData[asset].price).toString(),
|
|
457
|
+
isSupplied,
|
|
458
|
+
collateral: enabledAsCollateral,
|
|
459
|
+
stableBorrowRate: aprToApy(new Dec(tokenInfo.stableBorrowRate.toString()).div(1e25).toString()),
|
|
460
|
+
borrowedStable,
|
|
461
|
+
borrowedVariable,
|
|
462
|
+
borrowedUsdStable: new Dec(borrowedStable).mul(assetsData[asset].price).toString(),
|
|
463
|
+
borrowedUsdVariable: new Dec(borrowedVariable).mul(assetsData[asset].price).toString(),
|
|
464
|
+
borrowed,
|
|
465
|
+
borrowedUsd: new Dec(new Dec(borrowedVariable).add(borrowedStable)).mul(assetsData[asset].price).toString(),
|
|
466
|
+
isBorrowed,
|
|
467
|
+
interestMode,
|
|
468
|
+
};
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
payload.eModeCategory = +(eModeCategory as BigInt).toString();
|
|
472
|
+
payload = {
|
|
473
|
+
...payload,
|
|
474
|
+
usedAssets,
|
|
475
|
+
...aaveAnyGetAggregatedPositionData({
|
|
476
|
+
...extractedState, usedAssets, eModeCategory: payload.eModeCategory,
|
|
477
|
+
}),
|
|
478
|
+
};
|
|
479
|
+
payload.eModeCategories = aaveV3EmodeCategoriesMapping(extractedState, usedAssets);
|
|
480
|
+
payload.isInIsolationMode = aaveV3IsInIsolationMode({ usedAssets, assetsData });
|
|
481
|
+
payload.isInSiloedMode = aaveV3IsInSiloedMode({ usedAssets, assetsData });
|
|
482
|
+
|
|
483
|
+
payload.ratio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
484
|
+
? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
485
|
+
: '0';
|
|
486
|
+
payload.minRatio = '100';
|
|
487
|
+
payload.collRatio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
488
|
+
? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
489
|
+
: '0';
|
|
490
|
+
|
|
491
|
+
// Calculate borrow limits per asset
|
|
492
|
+
Object.values(payload.usedAssets).forEach((item) => {
|
|
493
|
+
if (item.isBorrowed) {
|
|
494
|
+
// eslint-disable-next-line no-param-reassign
|
|
495
|
+
item.stableLimit = calculateBorrowingAssetLimit(item.borrowedUsdStable, payload.borrowLimitUsd);
|
|
496
|
+
// eslint-disable-next-line no-param-reassign
|
|
497
|
+
item.variableLimit = calculateBorrowingAssetLimit(item.borrowedUsdVariable, payload.borrowLimitUsd);
|
|
498
|
+
// eslint-disable-next-line no-param-reassign
|
|
499
|
+
item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
|
|
503
|
+
payload.isSubscribedToAutomation = false;
|
|
504
|
+
payload.automationResubscribeRequired = false;
|
|
505
|
+
|
|
506
|
+
return payload;
|
|
507
|
+
};
|
|
508
|
+
|
|
509
|
+
export const getAaveV3AccountData = async (provider: EthereumProvider, network: NetworkNumber, address: EthAddress, extractedState: any, blockNumber: 'latest' | number = 'latest'): Promise<AaveV3PositionData> => _getAaveV3AccountData(getViemProvider(provider, network), network, address, extractedState, blockNumber);
|
|
510
|
+
|
|
511
|
+
export const getAaveV3FullPositionData = async (provider: EthereumProvider, network: NetworkNumber, address: EthAddress, market: AaveMarketInfo): Promise<AaveV3PositionData> => {
|
|
512
|
+
const marketData = await getAaveV3MarketData(provider, network, market);
|
|
513
|
+
const positionData = await getAaveV3AccountData(provider, network, address, { assetsData: marketData.assetsData, selectedMarket: market, eModeCategoriesData: marketData.eModeCategoriesData });
|
|
514
|
+
return positionData;
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
// aTokens eligible for AAVE rewards
|
|
518
|
+
export const REWARDABLE_ASSETS = [
|
|
519
|
+
'0x028171bCA77440897B824Ca71D1c56caC55b68A3', // DAI
|
|
520
|
+
'0x6C3c78838c761c6Ac7bE9F59fe808ea2A6E4379d',
|
|
521
|
+
'0xD37EE7e4f452C6638c96536e68090De8cBcdb583', // GUSD
|
|
522
|
+
'0x279AF5b99540c1A3A7E3CDd326e19659401eF99e',
|
|
523
|
+
'0xBcca60bB61934080951369a648Fb03DF4F96263C', // USDC
|
|
524
|
+
'0x619beb58998eD2278e08620f97007e1116D5D25b',
|
|
525
|
+
'0x3Ed3B47Dd13EC9a98b44e6204A523E766B225811', // USDT
|
|
526
|
+
'0x531842cEbbdD378f8ee36D171d6cC9C4fcf475Ec',
|
|
527
|
+
'0x9ff58f4fFB29fA2266Ab25e75e2A8b3503311656', // WBTC
|
|
528
|
+
'0x9c39809Dec7F95F5e0713634a4D0701329B3b4d2',
|
|
529
|
+
'0x030bA81f1c18d280636F32af80b9AAd02Cf0854e', // WETH
|
|
530
|
+
'0xF63B34710400CAd3e044cFfDcAb00a0f32E33eCf',
|
|
531
|
+
'0xa06bC25B5805d5F8d82847D191Cb4Af5A3e873E0', // LINK
|
|
532
|
+
'0x0b8f12b1788BFdE65Aa1ca52E3e9F3Ba401be16D',
|
|
533
|
+
'0x6C5024Cd4F8A59110119C56f8933403A539555EB', // SUSD
|
|
534
|
+
'0xdC6a3Ab17299D9C2A412B0e0a4C1f55446AE0817',
|
|
535
|
+
'0x5165d24277cD063F5ac44Efd447B27025e888f37', // YFI
|
|
536
|
+
'0x7EbD09022Be45AD993BAA1CEc61166Fcc8644d97',
|
|
537
|
+
'0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a', // xSUSHI
|
|
538
|
+
'0xfAFEDF95E21184E3d880bd56D4806c4b8d31c69A',
|
|
539
|
+
'0xB9D7CB55f463405CDfBe4E90a6D2Df01C2B92BF1', // UNI
|
|
540
|
+
'0x5BdB050A92CADcCfCDcCCBFC17204a1C9cC0Ab73',
|
|
541
|
+
'0xc713e5E149D5D0715DcD1c156a020976e7E56B88', // MKR
|
|
542
|
+
'0xba728eAd5e496BE00DCF66F650b6d7758eCB50f8',
|
|
543
|
+
'0x101cc05f4A51C0319f570d5E146a8C625198e636', // TUSD
|
|
544
|
+
'0x01C0eb1f8c6F1C1bF74ae028697ce7AA2a8b0E92',
|
|
545
|
+
'0xc9BC48c72154ef3e5425641a3c747242112a46AF', // RAI
|
|
546
|
+
'0xB5385132EE8321977FfF44b60cDE9fE9AB0B4e6b',
|
|
547
|
+
'0x272F97b7a56a387aE942350bBC7Df5700f8a4576', // BAL
|
|
548
|
+
'0x13210D4Fe0d5402bd7Ecbc4B5bC5cFcA3b71adB0',
|
|
549
|
+
'0x2e8f4bdbe3d47d7d7de490437aea9915d930f1a3', // USDP
|
|
550
|
+
'0xfdb93b3b10936cf81fa59a02a7523b6e2149b2b7',
|
|
551
|
+
'0xA361718326c15715591c299427c62086F69923D9', // BUSD
|
|
552
|
+
'0xbA429f7011c9fa04cDd46a2Da24dc0FF0aC6099c',
|
|
553
|
+
'0xd4937682df3C8aEF4FE912A96A74121C0829E664', // FRAX
|
|
554
|
+
'0xfE8F19B17fFeF0fDbfe2671F248903055AFAA8Ca',
|
|
555
|
+
'0x683923dB55Fead99A79Fa01A27EeC3cB19679cC3', // FEI
|
|
556
|
+
'0xC2e10006AccAb7B45D9184FcF5b7EC7763f5BaAe',
|
|
557
|
+
'0x8dAE6Cb04688C62d939ed9B68d32Bc62e49970b1', // CRV
|
|
558
|
+
'0x00ad8eBF64F141f1C81e9f8f792d3d1631c6c684',
|
|
559
|
+
'0x6F634c6135D2EBD550000ac92F494F9CB8183dAe', // DPI
|
|
560
|
+
'0x4dDff5885a67E4EffeC55875a3977D7E60F82ae0',
|
|
561
|
+
] as const;
|
|
562
|
+
|
|
563
|
+
export const fetchYearlyMeritApyForStakingGho = async () => {
|
|
564
|
+
try {
|
|
565
|
+
const response = await fetch('https://apps.aavechan.com/api/merit/aprs', { signal: AbortSignal.timeout(5000) });
|
|
566
|
+
const data = await response.json();
|
|
567
|
+
const apr = data?.currentAPR?.actionsAPR?.['ethereum-stkgho'] || '0' as string;
|
|
568
|
+
const apy = aprToApy(apr);
|
|
569
|
+
const apyWithDFSBonus = new Dec(apy).mul(1.05).toString(); // 5% bonus for DFS users
|
|
570
|
+
return apyWithDFSBonus;
|
|
571
|
+
} catch (e) {
|
|
572
|
+
const message = 'External API Failure: Failed to fetch yearly merit APY for staking GHO';
|
|
573
|
+
console.error(message, e);
|
|
574
|
+
return '0';
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
export const getStakeAaveData = async (provider: Client, network: NetworkNumber, address: EthAddress) => {
|
|
579
|
+
const stkGhoAddress = getAssetInfo('stkGHO').address as HexString;
|
|
580
|
+
const stkAaveAddress = getAssetInfo('stkAAVE').address as HexString;
|
|
581
|
+
|
|
582
|
+
const AaveIncentivesController = AaveIncentivesControllerViem(provider, network);
|
|
583
|
+
const stkAAVE = StkAAVEViem(provider, network);
|
|
584
|
+
const stkGHO = createViemContractFromConfigFunc('Erc20', stkGhoAddress as HexString)(provider, network);
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
const [aaveRewardsBalance, emissionsPerSecond, stkAAVEBalance, stkAAVETotalSupply, stkGHOBalance, ghoMeritApy] = await Promise.all([
|
|
588
|
+
AaveIncentivesController.read.getRewardsBalance([REWARDABLE_ASSETS, address]),
|
|
589
|
+
stkAAVE.read.assets([stkAaveAddress]),
|
|
590
|
+
stkAAVE.read.balanceOf([address]),
|
|
591
|
+
stkAAVE.read.totalSupply(),
|
|
592
|
+
stkGHO.read.balanceOf([address]),
|
|
593
|
+
fetchYearlyMeritApyForStakingGho(),
|
|
594
|
+
]);
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
const stkAaveApy = new Dec(assetAmountInEth(emissionsPerSecond[0].toString(), 'GHO') || 0).mul(SECONDS_PER_YEAR).mul(100).div(assetAmountInEth(stkAAVETotalSupply.toString(), 'stkAAVE'))
|
|
598
|
+
.toString();
|
|
599
|
+
return {
|
|
600
|
+
activatedCooldown: '0',
|
|
601
|
+
activatedCooldownAmount: '0',
|
|
602
|
+
stkAaveRewardsBalance: '0',
|
|
603
|
+
aaveRewardsBalance: assetAmountInEth(aaveRewardsBalance.toString(), 'AAVE'),
|
|
604
|
+
stkAaveBalance: assetAmountInEth(stkAAVEBalance.toString(), 'stkAAVE'),
|
|
605
|
+
stkGhoBalance: assetAmountInEth(stkGHOBalance.toString(), 'GHO'),
|
|
606
|
+
ghoMeritApy,
|
|
607
|
+
stkAaveApy,
|
|
608
|
+
};
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
export {
|
|
612
|
+
getMeritCampaigns,
|
|
613
|
+
getMerkleCampaigns,
|
|
614
|
+
};
|