@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/spark/index.ts
CHANGED
|
@@ -1,456 +1,456 @@
|
|
|
1
|
-
import Dec from 'decimal.js';
|
|
2
|
-
import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
|
|
3
|
-
import { Client } from 'viem';
|
|
4
|
-
import {
|
|
5
|
-
Blockish, EthAddress, EthereumProvider, IncentiveKind, NetworkNumber, PositionBalances,
|
|
6
|
-
} from '../types/common';
|
|
7
|
-
import {
|
|
8
|
-
ethToWeth, wethToEth, wethToEthByAddress,
|
|
9
|
-
} from '../services/utils';
|
|
10
|
-
import {
|
|
11
|
-
calculateNetApy, getStakingApy, STAKING_ASSETS,
|
|
12
|
-
} from '../staking';
|
|
13
|
-
import {
|
|
14
|
-
SparkViewContractViem,
|
|
15
|
-
SparkIncentiveDataProviderContractViem,
|
|
16
|
-
createViemContractFromConfigFunc,
|
|
17
|
-
} from '../contracts';
|
|
18
|
-
import {
|
|
19
|
-
SparkEModeCategoryDataMapping,
|
|
20
|
-
SparkAssetData,
|
|
21
|
-
SparkAssetsData,
|
|
22
|
-
SparkMarketData,
|
|
23
|
-
SparkMarketsData,
|
|
24
|
-
SparkPositionData,
|
|
25
|
-
SparkUsedAsset,
|
|
26
|
-
SparkUsedAssets,
|
|
27
|
-
EModeCategoriesData,
|
|
28
|
-
} from '../types';
|
|
29
|
-
import { sparkGetAggregatedPositionData, sparkIsInIsolationMode } from '../helpers/sparkHelpers';
|
|
30
|
-
import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
|
|
31
|
-
import { SPARK_V1 } from '../markets/spark';
|
|
32
|
-
import { getViemProvider, setViemBlockNumber } from '../services/viem';
|
|
33
|
-
|
|
34
|
-
export const sparkEmodeCategoriesMapping = (extractedState: { assetsData: SparkAssetsData }, usedAssets: SparkUsedAssets) => {
|
|
35
|
-
const { assetsData } = extractedState;
|
|
36
|
-
const usedAssetsValues = Object.values(usedAssets);
|
|
37
|
-
|
|
38
|
-
const categoriesMapping: { [key: number]: SparkEModeCategoryDataMapping } = {};
|
|
39
|
-
Object.values(assetsData).forEach((a) => {
|
|
40
|
-
const borrowingOnlyFromCategory = a.eModeCategory === 0
|
|
41
|
-
? true
|
|
42
|
-
: !usedAssetsValues.filter(u => u.isBorrowed && u.eModeCategory !== a.eModeCategory).length;
|
|
43
|
-
const afterEnteringCategory = sparkGetAggregatedPositionData({
|
|
44
|
-
...extractedState, usedAssets, eModeCategory: a.eModeCategory,
|
|
45
|
-
});
|
|
46
|
-
const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent);
|
|
47
|
-
const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized];
|
|
48
|
-
|
|
49
|
-
categoriesMapping[a.eModeCategory] = {
|
|
50
|
-
enteringTerms,
|
|
51
|
-
canEnterCategory: !enteringTerms.includes(false),
|
|
52
|
-
id: a.eModeCategory,
|
|
53
|
-
enabledData: {
|
|
54
|
-
ratio: afterEnteringCategory.ratio,
|
|
55
|
-
liqRatio: afterEnteringCategory.liqRatio,
|
|
56
|
-
liqPercent: afterEnteringCategory.liqPercent,
|
|
57
|
-
collRatio: afterEnteringCategory.collRatio,
|
|
58
|
-
},
|
|
59
|
-
};
|
|
60
|
-
});
|
|
61
|
-
return categoriesMapping;
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
export const _getSparkMarketsData = async (provider: Client, network: NetworkNumber, selectedMarket: SparkMarketData): Promise<SparkMarketsData> => {
|
|
65
|
-
const marketAddress = selectedMarket.providerAddress;
|
|
66
|
-
|
|
67
|
-
const loanInfoContract = SparkViewContractViem(provider, network);
|
|
68
|
-
const sparkIncentivesContract = SparkIncentiveDataProviderContractViem(provider, network);
|
|
69
|
-
|
|
70
|
-
// eslint-disable-next-line prefer-const
|
|
71
|
-
let [loanInfo, rewardInfo] = await Promise.all([
|
|
72
|
-
loanInfoContract.read.getFullTokensInfo([marketAddress, selectedMarket.assets.map(a => getAssetInfo(ethToWeth(a)).address) as EthAddress[]]),
|
|
73
|
-
sparkIncentivesContract.read.getReservesIncentivesData([marketAddress]),
|
|
74
|
-
]);
|
|
75
|
-
|
|
76
|
-
rewardInfo = rewardInfo.reduce((all: any, market: any) => {
|
|
77
|
-
// eslint-disable-next-line no-param-reassign
|
|
78
|
-
all[market.underlyingAsset] = market;
|
|
79
|
-
return all;
|
|
80
|
-
}, {});
|
|
81
|
-
|
|
82
|
-
const eModeCategoriesData: EModeCategoriesData = {};
|
|
83
|
-
|
|
84
|
-
const assetsData: SparkAssetData[] = await Promise.all(loanInfo
|
|
85
|
-
.map(async (market, i) => {
|
|
86
|
-
const symbol = selectedMarket.assets[i];
|
|
87
|
-
|
|
88
|
-
const borrowCapInWei = new Dec(assetAmountInWei(market.borrowCap.toString(), symbol));
|
|
89
|
-
let marketLiquidity = borrowCapInWei.lt(new Dec(market.totalSupply.toString()))
|
|
90
|
-
? assetAmountInEth(borrowCapInWei
|
|
91
|
-
.sub(market.totalBorrow.toString())
|
|
92
|
-
.toString(), symbol)
|
|
93
|
-
: assetAmountInEth(new Dec(market.totalSupply.toString())
|
|
94
|
-
.sub(market.totalBorrow.toString())
|
|
95
|
-
.toString(), symbol);
|
|
96
|
-
|
|
97
|
-
if (new Dec(marketLiquidity).lt(0)) {
|
|
98
|
-
marketLiquidity = '0';
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
eModeCategoriesData[+market.emodeCategory.toString()] = {
|
|
102
|
-
id: +market.emodeCategory.toString(),
|
|
103
|
-
label: market.label,
|
|
104
|
-
liquidationBonus: new Dec(market.liquidationBonus).div(10000).toString(),
|
|
105
|
-
liquidationRatio: new Dec(market.liquidationThreshold).div(10000).toString(),
|
|
106
|
-
collateralFactor: new Dec(market.ltv).div(10000).toString(),
|
|
107
|
-
collateralAssets: eModeCategoriesData[+market.emodeCategory.toString()] ? [...eModeCategoriesData[+market.emodeCategory.toString()].collateralAssets, selectedMarket.assets[i]] : [selectedMarket.assets[i]],
|
|
108
|
-
borrowAssets: eModeCategoriesData[+market.emodeCategory.toString()] ? [...eModeCategoriesData[+market.emodeCategory.toString()].borrowAssets, selectedMarket.assets[i]] : [selectedMarket.assets[i]],
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
return ({
|
|
112
|
-
symbol: selectedMarket.assets[i],
|
|
113
|
-
isIsolated: new Dec(market.debtCeilingForIsolationMode.toString()).gt(0),
|
|
114
|
-
debtCeilingForIsolationMode: new Dec(market.debtCeilingForIsolationMode.toString()).div(100).toString(),
|
|
115
|
-
isSiloed: market.isSiloedForBorrowing,
|
|
116
|
-
eModeCategory: +market.emodeCategory.toString(),
|
|
117
|
-
isolationModeTotalDebt: new Dec(market.isolationModeTotalDebt.toString()).div(100).toString(),
|
|
118
|
-
assetId: Number(market.assetId),
|
|
119
|
-
underlyingTokenAddress: market.underlyingTokenAddress,
|
|
120
|
-
supplyRate: aprToApy(new Dec(market.supplyRate.toString()).div(1e25).toString()),
|
|
121
|
-
borrowRate: aprToApy(new Dec(market.borrowRateVariable.toString()).div(1e25).toString()),
|
|
122
|
-
borrowRateStable: aprToApy(new Dec(market.borrowRateStable.toString()).div(1e25).toString()),
|
|
123
|
-
collateralFactor: new Dec(market.collateralFactor.toString()).div(10000).toString(),
|
|
124
|
-
liquidationRatio: new Dec(market.liquidationRatio.toString()).div(10000).toString(),
|
|
125
|
-
marketLiquidity,
|
|
126
|
-
utilization: new Dec(market.totalBorrow.toString()).times(100).div(new Dec(market.totalSupply.toString())).toString(),
|
|
127
|
-
usageAsCollateralEnabled: market.usageAsCollateralEnabled,
|
|
128
|
-
supplyCap: market.supplyCap.toString(),
|
|
129
|
-
borrowCap: market.borrowCap.toString(),
|
|
130
|
-
totalSupply: assetAmountInEth(market.totalSupply.toString(), selectedMarket.assets[i]),
|
|
131
|
-
isInactive: !market.isActive,
|
|
132
|
-
isFrozen: market.isFrozen,
|
|
133
|
-
isPaused: market.isPaused,
|
|
134
|
-
canBeBorrowed: market.isActive && !market.isPaused && !market.isFrozen && market.borrowingEnabled,
|
|
135
|
-
canBeSupplied: market.isActive && !market.isPaused && !market.isFrozen,
|
|
136
|
-
canBeWithdrawn: market.isActive && !market.isPaused,
|
|
137
|
-
canBePayBacked: market.isActive && !market.isPaused,
|
|
138
|
-
disabledStableBorrowing: !market.stableBorrowRateEnabled,
|
|
139
|
-
totalBorrow: assetAmountInEth(market.totalBorrow.toString(), selectedMarket.assets[i]),
|
|
140
|
-
totalBorrowVar: assetAmountInEth(market.totalBorrowVar.toString(), selectedMarket.assets[i]),
|
|
141
|
-
price: new Dec(market.price.toString()).div(1e8).toString(), // is actually price in USD
|
|
142
|
-
isolationModeBorrowingEnabled: market.isolationModeBorrowingEnabled,
|
|
143
|
-
isFlashLoanEnabled: market.isFlashLoanEnabled,
|
|
144
|
-
aTokenAddress: market.aTokenAddress,
|
|
145
|
-
supplyIncentives: [],
|
|
146
|
-
borrowIncentives: [],
|
|
147
|
-
});
|
|
148
|
-
}));
|
|
149
|
-
|
|
150
|
-
await Promise.all(assetsData.map(async (market) => {
|
|
151
|
-
/* eslint-disable no-param-reassign */
|
|
152
|
-
const rewardForMarket = (rewardInfo as any)[market.underlyingTokenAddress];
|
|
153
|
-
if (STAKING_ASSETS.includes(market.symbol)) {
|
|
154
|
-
const yieldApy = await getStakingApy(market.symbol);
|
|
155
|
-
market.supplyIncentives.push({
|
|
156
|
-
apy: yieldApy,
|
|
157
|
-
token: market.symbol,
|
|
158
|
-
incentiveKind: IncentiveKind.Staking,
|
|
159
|
-
description: `Native ${market.symbol} yield.`,
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
if (market.canBeBorrowed) {
|
|
163
|
-
if (!market.borrowIncentives) {
|
|
164
|
-
market.borrowIncentives = [];
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
market.borrowIncentives.push({
|
|
168
|
-
apy: new Dec(yieldApy).mul(-1).toString(),
|
|
169
|
-
token: market.symbol,
|
|
170
|
-
incentiveKind: IncentiveKind.Reward,
|
|
171
|
-
description: `Due to the native yield of ${market.symbol}, the value of the debt would increase over time.`,
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
if (!rewardForMarket) return;
|
|
177
|
-
(rewardForMarket.aIncentiveData.rewardsTokenInformation as any[]).forEach(supplyRewardData => {
|
|
178
|
-
if (supplyRewardData) {
|
|
179
|
-
if (+(supplyRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return;
|
|
180
|
-
const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond;
|
|
181
|
-
const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** supplyRewardData.priceFeedDecimals)
|
|
182
|
-
.toString();
|
|
183
|
-
const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** supplyRewardData.rewardTokenDecimals) / 100)
|
|
184
|
-
.mul(365 * 24 * 3600)
|
|
185
|
-
.mul(supplyRewardPrice)
|
|
186
|
-
.div(market.price)
|
|
187
|
-
.div(market.totalSupply)
|
|
188
|
-
.toString();
|
|
189
|
-
|
|
190
|
-
market.supplyIncentives.push({
|
|
191
|
-
token: supplyRewardData.rewardTokenSymbol,
|
|
192
|
-
apy: rewardApy,
|
|
193
|
-
incentiveKind: IncentiveKind.Reward,
|
|
194
|
-
description: 'Eligible for protocol-level incentives.',
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
});
|
|
198
|
-
(rewardForMarket.vIncentiveData.rewardsTokenInformation as any[]).forEach(borrowRewardData => {
|
|
199
|
-
if (borrowRewardData) {
|
|
200
|
-
if (+(borrowRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return;
|
|
201
|
-
const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond;
|
|
202
|
-
const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** borrowRewardData.priceFeedDecimals)
|
|
203
|
-
.toString();
|
|
204
|
-
const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** borrowRewardData.rewardTokenDecimals) / 100)
|
|
205
|
-
.mul(365 * 24 * 3600)
|
|
206
|
-
.mul(supplyRewardPrice)
|
|
207
|
-
.div(market.price)
|
|
208
|
-
.div(market.totalBorrowVar)
|
|
209
|
-
.toString();
|
|
210
|
-
market.borrowIncentives.push({
|
|
211
|
-
token: borrowRewardData.rewardTokenSymbol,
|
|
212
|
-
apy: rewardApy,
|
|
213
|
-
incentiveKind: IncentiveKind.Reward,
|
|
214
|
-
description: 'Eligible for protocol-level incentives.',
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
});
|
|
218
|
-
/* eslint-enable no-param-reassign */
|
|
219
|
-
}));
|
|
220
|
-
|
|
221
|
-
const filteredAssetsData: SparkAssetsData = {};
|
|
222
|
-
// Sort by market size
|
|
223
|
-
assetsData
|
|
224
|
-
.sort((a, b) => {
|
|
225
|
-
const aMarket = new Dec(a.price).times(a.totalSupply).toString();
|
|
226
|
-
const bMarket = new Dec(b.price).times(b.totalSupply).toString();
|
|
227
|
-
|
|
228
|
-
return new Dec(bMarket).minus(aMarket).toNumber();
|
|
229
|
-
})
|
|
230
|
-
.forEach((assetData: SparkAssetData, i) => {
|
|
231
|
-
filteredAssetsData[assetData.symbol] = { ...assetData, sortIndex: i };
|
|
232
|
-
});
|
|
233
|
-
|
|
234
|
-
eModeCategoriesData[0].collateralAssets = Object.values(filteredAssetsData).map(a => a.symbol);
|
|
235
|
-
eModeCategoriesData[0].borrowAssets = Object.values(filteredAssetsData).map(a => a.symbol);
|
|
236
|
-
|
|
237
|
-
return { assetsData: filteredAssetsData, eModeCategoriesData };
|
|
238
|
-
};
|
|
239
|
-
|
|
240
|
-
export const getSparkMarketsData = async (
|
|
241
|
-
provider: EthereumProvider,
|
|
242
|
-
network: NetworkNumber,
|
|
243
|
-
selectedMarket: SparkMarketData,
|
|
244
|
-
): Promise<SparkMarketsData> => _getSparkMarketsData(getViemProvider(provider, network), network, selectedMarket);
|
|
245
|
-
|
|
246
|
-
export const EMPTY_SPARK_DATA = {
|
|
247
|
-
usedAssets: {},
|
|
248
|
-
suppliedUsd: '0',
|
|
249
|
-
borrowedUsd: '0',
|
|
250
|
-
borrowLimitUsd: '0',
|
|
251
|
-
leftToBorrowUsd: '0',
|
|
252
|
-
ratio: '0',
|
|
253
|
-
minRatio: '0',
|
|
254
|
-
netApy: '0',
|
|
255
|
-
incentiveUsd: '0',
|
|
256
|
-
totalInterestUsd: '0',
|
|
257
|
-
eModeCategory: 0,
|
|
258
|
-
isInIsolationMode: false,
|
|
259
|
-
isInSiloedMode: false,
|
|
260
|
-
collRatio: '0',
|
|
261
|
-
suppliedCollateralUsd: '0',
|
|
262
|
-
totalSupplied: '0',
|
|
263
|
-
eModeCategories: [],
|
|
264
|
-
};
|
|
265
|
-
|
|
266
|
-
export const _getSparkAccountBalances = async (provider: Client, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
|
|
267
|
-
let balances: PositionBalances = {
|
|
268
|
-
collateral: {},
|
|
269
|
-
debt: {},
|
|
270
|
-
};
|
|
271
|
-
|
|
272
|
-
if (!address) {
|
|
273
|
-
return balances;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
const loanInfoContract = SparkViewContractViem(provider, network, block);
|
|
277
|
-
|
|
278
|
-
const market = SPARK_V1(network);
|
|
279
|
-
const marketAddress = market.providerAddress;
|
|
280
|
-
// @ts-ignore
|
|
281
|
-
const protocolDataProviderContract = createViemContractFromConfigFunc(market.protocolData, market.protocolDataAddress)(provider, network);
|
|
282
|
-
|
|
283
|
-
// @ts-ignore
|
|
284
|
-
const reserveTokens = await protocolDataProviderContract.read.getAllReservesTokens(setViemBlockNumber(block)) as { symbol: string, tokenAddress: EthAddress }[];
|
|
285
|
-
const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
|
|
286
|
-
const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
// split addresses in half to avoid gas limit by multicall
|
|
290
|
-
const middleAddressIndex = Math.floor(_addresses.length / 2);
|
|
291
|
-
|
|
292
|
-
const [tokenBalances1, tokenBalances2] = await Promise.all([
|
|
293
|
-
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex)], setViemBlockNumber(block)),
|
|
294
|
-
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)], setViemBlockNumber(block)),
|
|
295
|
-
]);
|
|
296
|
-
|
|
297
|
-
const loanInfo = [...tokenBalances1, ...tokenBalances2];
|
|
298
|
-
|
|
299
|
-
loanInfo.forEach((tokenInfo: any, i: number) => {
|
|
300
|
-
const asset = wethToEth(symbols[i]);
|
|
301
|
-
const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
|
|
302
|
-
|
|
303
|
-
balances = {
|
|
304
|
-
collateral: {
|
|
305
|
-
...balances.collateral,
|
|
306
|
-
[addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
|
|
307
|
-
},
|
|
308
|
-
debt: {
|
|
309
|
-
...balances.debt,
|
|
310
|
-
[addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
|
|
311
|
-
},
|
|
312
|
-
};
|
|
313
|
-
});
|
|
314
|
-
|
|
315
|
-
return balances;
|
|
316
|
-
};
|
|
317
|
-
|
|
318
|
-
export const getSparkAccountBalances = async (
|
|
319
|
-
provider: EthereumProvider,
|
|
320
|
-
network: NetworkNumber,
|
|
321
|
-
block: Blockish,
|
|
322
|
-
addressMapping: boolean,
|
|
323
|
-
address: EthAddress,
|
|
324
|
-
): Promise<PositionBalances> => _getSparkAccountBalances(getViemProvider(provider, network, { batch: { multicall: true } }), network, block, addressMapping, address);
|
|
325
|
-
|
|
326
|
-
export const _getSparkAccountData = async (
|
|
327
|
-
provider: Client,
|
|
328
|
-
network: NetworkNumber,
|
|
329
|
-
address: EthAddress,
|
|
330
|
-
extractedState: { selectedMarket: SparkMarketData, assetsData: SparkAssetsData, eModeCategoriesData: EModeCategoriesData },
|
|
331
|
-
) => {
|
|
332
|
-
const {
|
|
333
|
-
selectedMarket: market, assetsData,
|
|
334
|
-
} = extractedState;
|
|
335
|
-
let payload: SparkPositionData = {
|
|
336
|
-
...EMPTY_SPARK_DATA,
|
|
337
|
-
lastUpdated: Date.now(),
|
|
338
|
-
};
|
|
339
|
-
if (!address) {
|
|
340
|
-
// structure that this function returns is complex and dynamic so i didnt want to hardcode it in EMPTY_SPARK_DATA
|
|
341
|
-
// This case only triggers if user doesnt have proxy and data is refetched once proxy is created
|
|
342
|
-
// TODO when refactoring spark figure out if this is the best solution.
|
|
343
|
-
payload.eModeCategories = sparkEmodeCategoriesMapping(extractedState, {});
|
|
344
|
-
|
|
345
|
-
return payload;
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
const loanInfoContract = SparkViewContractViem(provider, network);
|
|
349
|
-
const lendingPoolContract = createViemContractFromConfigFunc(market.lendingPool, market.lendingPoolAddress)(provider, network);
|
|
350
|
-
|
|
351
|
-
const marketAddress = market.providerAddress;
|
|
352
|
-
const _addresses = market.assets.map((a) => getAssetInfo(ethToWeth(a)).address);
|
|
353
|
-
|
|
354
|
-
const middleAddressIndex = Math.floor(_addresses.length / 2); // split addresses in half to avoid gas limit by multicall
|
|
355
|
-
|
|
356
|
-
const [userEMode, tokenBalances1, tokenBalances2] = await Promise.all([
|
|
357
|
-
lendingPoolContract.read.getUserEMode([address]),
|
|
358
|
-
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex) as EthAddress[]]),
|
|
359
|
-
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length) as EthAddress[]]),
|
|
360
|
-
]);
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
const loanInfo = [...tokenBalances1, ...tokenBalances2];
|
|
364
|
-
|
|
365
|
-
const usedAssets = {} as SparkUsedAssets;
|
|
366
|
-
loanInfo.forEach((tokenInfo, i) => {
|
|
367
|
-
const asset = market.assets[i];
|
|
368
|
-
const isSupplied = tokenInfo.balance.toString() !== '0';
|
|
369
|
-
const isBorrowed = tokenInfo.borrowsStable.toString() !== '0' || tokenInfo.borrowsVariable.toString() !== '0';
|
|
370
|
-
if (!isSupplied && !isBorrowed) return;
|
|
371
|
-
|
|
372
|
-
const supplied = assetAmountInEth(tokenInfo.balance.toString(), asset);
|
|
373
|
-
const borrowedStable = assetAmountInEth(tokenInfo.borrowsStable.toString(), asset);
|
|
374
|
-
const borrowedVariable = assetAmountInEth(tokenInfo.borrowsVariable.toString(), asset);
|
|
375
|
-
const enabledAsCollateral = assetsData[asset].usageAsCollateralEnabled ? tokenInfo.enabledAsCollateral : false;
|
|
376
|
-
let interestMode;
|
|
377
|
-
if (borrowedVariable === '0' && borrowedStable !== '0') {
|
|
378
|
-
interestMode = '1';
|
|
379
|
-
} else if (borrowedVariable !== '0' && borrowedStable === '0') {
|
|
380
|
-
interestMode = '2';
|
|
381
|
-
} else {
|
|
382
|
-
interestMode = 'both';
|
|
383
|
-
}
|
|
384
|
-
if (!usedAssets[asset]) usedAssets[asset] = {} as SparkUsedAsset;
|
|
385
|
-
usedAssets[asset] = {
|
|
386
|
-
...usedAssets[asset],
|
|
387
|
-
symbol: asset,
|
|
388
|
-
supplied,
|
|
389
|
-
suppliedUsd: new Dec(supplied).mul(assetsData[asset].price).toString(),
|
|
390
|
-
isSupplied,
|
|
391
|
-
collateral: enabledAsCollateral,
|
|
392
|
-
stableBorrowRate: aprToApy(new Dec(tokenInfo.stableBorrowRate.toString()).div(1e25).toString()),
|
|
393
|
-
borrowedStable,
|
|
394
|
-
borrowedVariable,
|
|
395
|
-
borrowedUsdStable: new Dec(borrowedStable).mul(assetsData[asset].price).toString(),
|
|
396
|
-
borrowedUsdVariable: new Dec(borrowedVariable).mul(assetsData[asset].price).toString(),
|
|
397
|
-
borrowed: new Dec(borrowedStable).add(borrowedVariable).toString(),
|
|
398
|
-
borrowedUsd: new Dec(new Dec(borrowedVariable).add(borrowedStable)).mul(assetsData[asset].price).toString(),
|
|
399
|
-
isBorrowed,
|
|
400
|
-
eModeCategory: assetsData[asset].eModeCategory,
|
|
401
|
-
interestMode,
|
|
402
|
-
};
|
|
403
|
-
});
|
|
404
|
-
|
|
405
|
-
payload.eModeCategory = +userEMode.toString();
|
|
406
|
-
payload = {
|
|
407
|
-
...payload,
|
|
408
|
-
usedAssets,
|
|
409
|
-
...sparkGetAggregatedPositionData({
|
|
410
|
-
...extractedState, usedAssets, eModeCategory: payload.eModeCategory,
|
|
411
|
-
}),
|
|
412
|
-
};
|
|
413
|
-
payload.eModeCategories = sparkEmodeCategoriesMapping(extractedState, usedAssets);
|
|
414
|
-
payload.isInIsolationMode = sparkIsInIsolationMode({ usedAssets, assetsData });
|
|
415
|
-
payload.isInSiloedMode = sparkIsInIsolationMode({ usedAssets, assetsData });
|
|
416
|
-
|
|
417
|
-
payload.ratio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
418
|
-
? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
419
|
-
: '0';
|
|
420
|
-
payload.minRatio = '100';
|
|
421
|
-
payload.collRatio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
422
|
-
? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
423
|
-
: '0';
|
|
424
|
-
|
|
425
|
-
// Calculate borrow limits per asset
|
|
426
|
-
Object.values(payload.usedAssets).forEach((item) => {
|
|
427
|
-
if (item.isBorrowed) {
|
|
428
|
-
// eslint-disable-next-line no-param-reassign
|
|
429
|
-
item.stableLimit = calculateBorrowingAssetLimit(item.borrowedUsdStable, payload.borrowLimitUsd);
|
|
430
|
-
// eslint-disable-next-line no-param-reassign
|
|
431
|
-
item.variableLimit = calculateBorrowingAssetLimit(item.borrowedUsdVariable, payload.borrowLimitUsd);
|
|
432
|
-
// eslint-disable-next-line no-param-reassign
|
|
433
|
-
item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
|
|
434
|
-
}
|
|
435
|
-
});
|
|
436
|
-
|
|
437
|
-
const { netApy, incentiveUsd, totalInterestUsd } = calculateNetApy({ usedAssets, assetsData });
|
|
438
|
-
payload.netApy = netApy;
|
|
439
|
-
payload.incentiveUsd = incentiveUsd;
|
|
440
|
-
payload.totalInterestUsd = totalInterestUsd;
|
|
441
|
-
|
|
442
|
-
return payload;
|
|
443
|
-
};
|
|
444
|
-
|
|
445
|
-
export const getSparkAccountData = async (
|
|
446
|
-
provider: EthereumProvider,
|
|
447
|
-
network: NetworkNumber,
|
|
448
|
-
address: EthAddress,
|
|
449
|
-
extractedState: { selectedMarket: SparkMarketData, assetsData: SparkAssetsData, eModeCategoriesData: EModeCategoriesData },
|
|
450
|
-
) => _getSparkAccountData(getViemProvider(provider, network), network, address, extractedState);
|
|
451
|
-
|
|
452
|
-
export const getSparkFullPositionData = async (provider: EthereumProvider, network: NetworkNumber, address: EthAddress, market: SparkMarketData): Promise<SparkPositionData> => {
|
|
453
|
-
const marketData = await getSparkMarketsData(provider, network, market);
|
|
454
|
-
const positionData = await getSparkAccountData(provider, network, address, { assetsData: marketData.assetsData, selectedMarket: market, eModeCategoriesData: marketData.eModeCategoriesData });
|
|
455
|
-
return positionData;
|
|
456
|
-
};
|
|
1
|
+
import Dec from 'decimal.js';
|
|
2
|
+
import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
|
|
3
|
+
import { Client } from 'viem';
|
|
4
|
+
import {
|
|
5
|
+
Blockish, EthAddress, EthereumProvider, IncentiveKind, NetworkNumber, PositionBalances,
|
|
6
|
+
} from '../types/common';
|
|
7
|
+
import {
|
|
8
|
+
ethToWeth, wethToEth, wethToEthByAddress,
|
|
9
|
+
} from '../services/utils';
|
|
10
|
+
import {
|
|
11
|
+
calculateNetApy, getStakingApy, STAKING_ASSETS,
|
|
12
|
+
} from '../staking';
|
|
13
|
+
import {
|
|
14
|
+
SparkViewContractViem,
|
|
15
|
+
SparkIncentiveDataProviderContractViem,
|
|
16
|
+
createViemContractFromConfigFunc,
|
|
17
|
+
} from '../contracts';
|
|
18
|
+
import {
|
|
19
|
+
SparkEModeCategoryDataMapping,
|
|
20
|
+
SparkAssetData,
|
|
21
|
+
SparkAssetsData,
|
|
22
|
+
SparkMarketData,
|
|
23
|
+
SparkMarketsData,
|
|
24
|
+
SparkPositionData,
|
|
25
|
+
SparkUsedAsset,
|
|
26
|
+
SparkUsedAssets,
|
|
27
|
+
EModeCategoriesData,
|
|
28
|
+
} from '../types';
|
|
29
|
+
import { sparkGetAggregatedPositionData, sparkIsInIsolationMode } from '../helpers/sparkHelpers';
|
|
30
|
+
import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
|
|
31
|
+
import { SPARK_V1 } from '../markets/spark';
|
|
32
|
+
import { getViemProvider, setViemBlockNumber } from '../services/viem';
|
|
33
|
+
|
|
34
|
+
export const sparkEmodeCategoriesMapping = (extractedState: { assetsData: SparkAssetsData }, usedAssets: SparkUsedAssets) => {
|
|
35
|
+
const { assetsData } = extractedState;
|
|
36
|
+
const usedAssetsValues = Object.values(usedAssets);
|
|
37
|
+
|
|
38
|
+
const categoriesMapping: { [key: number]: SparkEModeCategoryDataMapping } = {};
|
|
39
|
+
Object.values(assetsData).forEach((a) => {
|
|
40
|
+
const borrowingOnlyFromCategory = a.eModeCategory === 0
|
|
41
|
+
? true
|
|
42
|
+
: !usedAssetsValues.filter(u => u.isBorrowed && u.eModeCategory !== a.eModeCategory).length;
|
|
43
|
+
const afterEnteringCategory = sparkGetAggregatedPositionData({
|
|
44
|
+
...extractedState, usedAssets, eModeCategory: a.eModeCategory,
|
|
45
|
+
});
|
|
46
|
+
const willStayOverCollateralized = new Dec(afterEnteringCategory.ratio).eq(0) || new Dec(afterEnteringCategory.ratio).gt(afterEnteringCategory.liqPercent);
|
|
47
|
+
const enteringTerms = [borrowingOnlyFromCategory, willStayOverCollateralized];
|
|
48
|
+
|
|
49
|
+
categoriesMapping[a.eModeCategory] = {
|
|
50
|
+
enteringTerms,
|
|
51
|
+
canEnterCategory: !enteringTerms.includes(false),
|
|
52
|
+
id: a.eModeCategory,
|
|
53
|
+
enabledData: {
|
|
54
|
+
ratio: afterEnteringCategory.ratio,
|
|
55
|
+
liqRatio: afterEnteringCategory.liqRatio,
|
|
56
|
+
liqPercent: afterEnteringCategory.liqPercent,
|
|
57
|
+
collRatio: afterEnteringCategory.collRatio,
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
return categoriesMapping;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const _getSparkMarketsData = async (provider: Client, network: NetworkNumber, selectedMarket: SparkMarketData): Promise<SparkMarketsData> => {
|
|
65
|
+
const marketAddress = selectedMarket.providerAddress;
|
|
66
|
+
|
|
67
|
+
const loanInfoContract = SparkViewContractViem(provider, network);
|
|
68
|
+
const sparkIncentivesContract = SparkIncentiveDataProviderContractViem(provider, network);
|
|
69
|
+
|
|
70
|
+
// eslint-disable-next-line prefer-const
|
|
71
|
+
let [loanInfo, rewardInfo] = await Promise.all([
|
|
72
|
+
loanInfoContract.read.getFullTokensInfo([marketAddress, selectedMarket.assets.map(a => getAssetInfo(ethToWeth(a)).address) as EthAddress[]]),
|
|
73
|
+
sparkIncentivesContract.read.getReservesIncentivesData([marketAddress]),
|
|
74
|
+
]);
|
|
75
|
+
|
|
76
|
+
rewardInfo = rewardInfo.reduce((all: any, market: any) => {
|
|
77
|
+
// eslint-disable-next-line no-param-reassign
|
|
78
|
+
all[market.underlyingAsset] = market;
|
|
79
|
+
return all;
|
|
80
|
+
}, {});
|
|
81
|
+
|
|
82
|
+
const eModeCategoriesData: EModeCategoriesData = {};
|
|
83
|
+
|
|
84
|
+
const assetsData: SparkAssetData[] = await Promise.all(loanInfo
|
|
85
|
+
.map(async (market, i) => {
|
|
86
|
+
const symbol = selectedMarket.assets[i];
|
|
87
|
+
|
|
88
|
+
const borrowCapInWei = new Dec(assetAmountInWei(market.borrowCap.toString(), symbol));
|
|
89
|
+
let marketLiquidity = borrowCapInWei.lt(new Dec(market.totalSupply.toString()))
|
|
90
|
+
? assetAmountInEth(borrowCapInWei
|
|
91
|
+
.sub(market.totalBorrow.toString())
|
|
92
|
+
.toString(), symbol)
|
|
93
|
+
: assetAmountInEth(new Dec(market.totalSupply.toString())
|
|
94
|
+
.sub(market.totalBorrow.toString())
|
|
95
|
+
.toString(), symbol);
|
|
96
|
+
|
|
97
|
+
if (new Dec(marketLiquidity).lt(0)) {
|
|
98
|
+
marketLiquidity = '0';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
eModeCategoriesData[+market.emodeCategory.toString()] = {
|
|
102
|
+
id: +market.emodeCategory.toString(),
|
|
103
|
+
label: market.label,
|
|
104
|
+
liquidationBonus: new Dec(market.liquidationBonus).div(10000).toString(),
|
|
105
|
+
liquidationRatio: new Dec(market.liquidationThreshold).div(10000).toString(),
|
|
106
|
+
collateralFactor: new Dec(market.ltv).div(10000).toString(),
|
|
107
|
+
collateralAssets: eModeCategoriesData[+market.emodeCategory.toString()] ? [...eModeCategoriesData[+market.emodeCategory.toString()].collateralAssets, selectedMarket.assets[i]] : [selectedMarket.assets[i]],
|
|
108
|
+
borrowAssets: eModeCategoriesData[+market.emodeCategory.toString()] ? [...eModeCategoriesData[+market.emodeCategory.toString()].borrowAssets, selectedMarket.assets[i]] : [selectedMarket.assets[i]],
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
return ({
|
|
112
|
+
symbol: selectedMarket.assets[i],
|
|
113
|
+
isIsolated: new Dec(market.debtCeilingForIsolationMode.toString()).gt(0),
|
|
114
|
+
debtCeilingForIsolationMode: new Dec(market.debtCeilingForIsolationMode.toString()).div(100).toString(),
|
|
115
|
+
isSiloed: market.isSiloedForBorrowing,
|
|
116
|
+
eModeCategory: +market.emodeCategory.toString(),
|
|
117
|
+
isolationModeTotalDebt: new Dec(market.isolationModeTotalDebt.toString()).div(100).toString(),
|
|
118
|
+
assetId: Number(market.assetId),
|
|
119
|
+
underlyingTokenAddress: market.underlyingTokenAddress,
|
|
120
|
+
supplyRate: aprToApy(new Dec(market.supplyRate.toString()).div(1e25).toString()),
|
|
121
|
+
borrowRate: aprToApy(new Dec(market.borrowRateVariable.toString()).div(1e25).toString()),
|
|
122
|
+
borrowRateStable: aprToApy(new Dec(market.borrowRateStable.toString()).div(1e25).toString()),
|
|
123
|
+
collateralFactor: new Dec(market.collateralFactor.toString()).div(10000).toString(),
|
|
124
|
+
liquidationRatio: new Dec(market.liquidationRatio.toString()).div(10000).toString(),
|
|
125
|
+
marketLiquidity,
|
|
126
|
+
utilization: new Dec(market.totalBorrow.toString()).times(100).div(new Dec(market.totalSupply.toString())).toString(),
|
|
127
|
+
usageAsCollateralEnabled: market.usageAsCollateralEnabled,
|
|
128
|
+
supplyCap: market.supplyCap.toString(),
|
|
129
|
+
borrowCap: market.borrowCap.toString(),
|
|
130
|
+
totalSupply: assetAmountInEth(market.totalSupply.toString(), selectedMarket.assets[i]),
|
|
131
|
+
isInactive: !market.isActive,
|
|
132
|
+
isFrozen: market.isFrozen,
|
|
133
|
+
isPaused: market.isPaused,
|
|
134
|
+
canBeBorrowed: market.isActive && !market.isPaused && !market.isFrozen && market.borrowingEnabled,
|
|
135
|
+
canBeSupplied: market.isActive && !market.isPaused && !market.isFrozen,
|
|
136
|
+
canBeWithdrawn: market.isActive && !market.isPaused,
|
|
137
|
+
canBePayBacked: market.isActive && !market.isPaused,
|
|
138
|
+
disabledStableBorrowing: !market.stableBorrowRateEnabled,
|
|
139
|
+
totalBorrow: assetAmountInEth(market.totalBorrow.toString(), selectedMarket.assets[i]),
|
|
140
|
+
totalBorrowVar: assetAmountInEth(market.totalBorrowVar.toString(), selectedMarket.assets[i]),
|
|
141
|
+
price: new Dec(market.price.toString()).div(1e8).toString(), // is actually price in USD
|
|
142
|
+
isolationModeBorrowingEnabled: market.isolationModeBorrowingEnabled,
|
|
143
|
+
isFlashLoanEnabled: market.isFlashLoanEnabled,
|
|
144
|
+
aTokenAddress: market.aTokenAddress,
|
|
145
|
+
supplyIncentives: [],
|
|
146
|
+
borrowIncentives: [],
|
|
147
|
+
});
|
|
148
|
+
}));
|
|
149
|
+
|
|
150
|
+
await Promise.all(assetsData.map(async (market) => {
|
|
151
|
+
/* eslint-disable no-param-reassign */
|
|
152
|
+
const rewardForMarket = (rewardInfo as any)[market.underlyingTokenAddress];
|
|
153
|
+
if (STAKING_ASSETS.includes(market.symbol)) {
|
|
154
|
+
const yieldApy = await getStakingApy(market.symbol);
|
|
155
|
+
market.supplyIncentives.push({
|
|
156
|
+
apy: yieldApy,
|
|
157
|
+
token: market.symbol,
|
|
158
|
+
incentiveKind: IncentiveKind.Staking,
|
|
159
|
+
description: `Native ${market.symbol} yield.`,
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
if (market.canBeBorrowed) {
|
|
163
|
+
if (!market.borrowIncentives) {
|
|
164
|
+
market.borrowIncentives = [];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
market.borrowIncentives.push({
|
|
168
|
+
apy: new Dec(yieldApy).mul(-1).toString(),
|
|
169
|
+
token: market.symbol,
|
|
170
|
+
incentiveKind: IncentiveKind.Reward,
|
|
171
|
+
description: `Due to the native yield of ${market.symbol}, the value of the debt would increase over time.`,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (!rewardForMarket) return;
|
|
177
|
+
(rewardForMarket.aIncentiveData.rewardsTokenInformation as any[]).forEach(supplyRewardData => {
|
|
178
|
+
if (supplyRewardData) {
|
|
179
|
+
if (+(supplyRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return;
|
|
180
|
+
const supplyEmissionPerSecond = supplyRewardData.emissionPerSecond;
|
|
181
|
+
const supplyRewardPrice = new Dec(supplyRewardData.rewardPriceFeed).div(10 ** supplyRewardData.priceFeedDecimals)
|
|
182
|
+
.toString();
|
|
183
|
+
const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** supplyRewardData.rewardTokenDecimals) / 100)
|
|
184
|
+
.mul(365 * 24 * 3600)
|
|
185
|
+
.mul(supplyRewardPrice)
|
|
186
|
+
.div(market.price)
|
|
187
|
+
.div(market.totalSupply)
|
|
188
|
+
.toString();
|
|
189
|
+
|
|
190
|
+
market.supplyIncentives.push({
|
|
191
|
+
token: supplyRewardData.rewardTokenSymbol,
|
|
192
|
+
apy: rewardApy,
|
|
193
|
+
incentiveKind: IncentiveKind.Reward,
|
|
194
|
+
description: 'Eligible for protocol-level incentives.',
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
(rewardForMarket.vIncentiveData.rewardsTokenInformation as any[]).forEach(borrowRewardData => {
|
|
199
|
+
if (borrowRewardData) {
|
|
200
|
+
if (+(borrowRewardData.emissionEndTimestamp.toString()) * 1000 < Date.now()) return;
|
|
201
|
+
const supplyEmissionPerSecond = borrowRewardData.emissionPerSecond;
|
|
202
|
+
const supplyRewardPrice = new Dec(borrowRewardData.rewardPriceFeed).div(10 ** borrowRewardData.priceFeedDecimals)
|
|
203
|
+
.toString();
|
|
204
|
+
const rewardApy = new Dec(supplyEmissionPerSecond).div((10 ** borrowRewardData.rewardTokenDecimals) / 100)
|
|
205
|
+
.mul(365 * 24 * 3600)
|
|
206
|
+
.mul(supplyRewardPrice)
|
|
207
|
+
.div(market.price)
|
|
208
|
+
.div(market.totalBorrowVar)
|
|
209
|
+
.toString();
|
|
210
|
+
market.borrowIncentives.push({
|
|
211
|
+
token: borrowRewardData.rewardTokenSymbol,
|
|
212
|
+
apy: rewardApy,
|
|
213
|
+
incentiveKind: IncentiveKind.Reward,
|
|
214
|
+
description: 'Eligible for protocol-level incentives.',
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
/* eslint-enable no-param-reassign */
|
|
219
|
+
}));
|
|
220
|
+
|
|
221
|
+
const filteredAssetsData: SparkAssetsData = {};
|
|
222
|
+
// Sort by market size
|
|
223
|
+
assetsData
|
|
224
|
+
.sort((a, b) => {
|
|
225
|
+
const aMarket = new Dec(a.price).times(a.totalSupply).toString();
|
|
226
|
+
const bMarket = new Dec(b.price).times(b.totalSupply).toString();
|
|
227
|
+
|
|
228
|
+
return new Dec(bMarket).minus(aMarket).toNumber();
|
|
229
|
+
})
|
|
230
|
+
.forEach((assetData: SparkAssetData, i) => {
|
|
231
|
+
filteredAssetsData[assetData.symbol] = { ...assetData, sortIndex: i };
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
eModeCategoriesData[0].collateralAssets = Object.values(filteredAssetsData).map(a => a.symbol);
|
|
235
|
+
eModeCategoriesData[0].borrowAssets = Object.values(filteredAssetsData).map(a => a.symbol);
|
|
236
|
+
|
|
237
|
+
return { assetsData: filteredAssetsData, eModeCategoriesData };
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
export const getSparkMarketsData = async (
|
|
241
|
+
provider: EthereumProvider,
|
|
242
|
+
network: NetworkNumber,
|
|
243
|
+
selectedMarket: SparkMarketData,
|
|
244
|
+
): Promise<SparkMarketsData> => _getSparkMarketsData(getViemProvider(provider, network), network, selectedMarket);
|
|
245
|
+
|
|
246
|
+
export const EMPTY_SPARK_DATA = {
|
|
247
|
+
usedAssets: {},
|
|
248
|
+
suppliedUsd: '0',
|
|
249
|
+
borrowedUsd: '0',
|
|
250
|
+
borrowLimitUsd: '0',
|
|
251
|
+
leftToBorrowUsd: '0',
|
|
252
|
+
ratio: '0',
|
|
253
|
+
minRatio: '0',
|
|
254
|
+
netApy: '0',
|
|
255
|
+
incentiveUsd: '0',
|
|
256
|
+
totalInterestUsd: '0',
|
|
257
|
+
eModeCategory: 0,
|
|
258
|
+
isInIsolationMode: false,
|
|
259
|
+
isInSiloedMode: false,
|
|
260
|
+
collRatio: '0',
|
|
261
|
+
suppliedCollateralUsd: '0',
|
|
262
|
+
totalSupplied: '0',
|
|
263
|
+
eModeCategories: [],
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
export const _getSparkAccountBalances = async (provider: Client, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
|
|
267
|
+
let balances: PositionBalances = {
|
|
268
|
+
collateral: {},
|
|
269
|
+
debt: {},
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
if (!address) {
|
|
273
|
+
return balances;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const loanInfoContract = SparkViewContractViem(provider, network, block);
|
|
277
|
+
|
|
278
|
+
const market = SPARK_V1(network);
|
|
279
|
+
const marketAddress = market.providerAddress;
|
|
280
|
+
// @ts-ignore
|
|
281
|
+
const protocolDataProviderContract = createViemContractFromConfigFunc(market.protocolData, market.protocolDataAddress)(provider, network);
|
|
282
|
+
|
|
283
|
+
// @ts-ignore
|
|
284
|
+
const reserveTokens = await protocolDataProviderContract.read.getAllReservesTokens(setViemBlockNumber(block)) as { symbol: string, tokenAddress: EthAddress }[];
|
|
285
|
+
const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
|
|
286
|
+
const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
// split addresses in half to avoid gas limit by multicall
|
|
290
|
+
const middleAddressIndex = Math.floor(_addresses.length / 2);
|
|
291
|
+
|
|
292
|
+
const [tokenBalances1, tokenBalances2] = await Promise.all([
|
|
293
|
+
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex)], setViemBlockNumber(block)),
|
|
294
|
+
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)], setViemBlockNumber(block)),
|
|
295
|
+
]);
|
|
296
|
+
|
|
297
|
+
const loanInfo = [...tokenBalances1, ...tokenBalances2];
|
|
298
|
+
|
|
299
|
+
loanInfo.forEach((tokenInfo: any, i: number) => {
|
|
300
|
+
const asset = wethToEth(symbols[i]);
|
|
301
|
+
const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
|
|
302
|
+
|
|
303
|
+
balances = {
|
|
304
|
+
collateral: {
|
|
305
|
+
...balances.collateral,
|
|
306
|
+
[addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
|
|
307
|
+
},
|
|
308
|
+
debt: {
|
|
309
|
+
...balances.debt,
|
|
310
|
+
[addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
return balances;
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
export const getSparkAccountBalances = async (
|
|
319
|
+
provider: EthereumProvider,
|
|
320
|
+
network: NetworkNumber,
|
|
321
|
+
block: Blockish,
|
|
322
|
+
addressMapping: boolean,
|
|
323
|
+
address: EthAddress,
|
|
324
|
+
): Promise<PositionBalances> => _getSparkAccountBalances(getViemProvider(provider, network, { batch: { multicall: true } }), network, block, addressMapping, address);
|
|
325
|
+
|
|
326
|
+
export const _getSparkAccountData = async (
|
|
327
|
+
provider: Client,
|
|
328
|
+
network: NetworkNumber,
|
|
329
|
+
address: EthAddress,
|
|
330
|
+
extractedState: { selectedMarket: SparkMarketData, assetsData: SparkAssetsData, eModeCategoriesData: EModeCategoriesData },
|
|
331
|
+
) => {
|
|
332
|
+
const {
|
|
333
|
+
selectedMarket: market, assetsData,
|
|
334
|
+
} = extractedState;
|
|
335
|
+
let payload: SparkPositionData = {
|
|
336
|
+
...EMPTY_SPARK_DATA,
|
|
337
|
+
lastUpdated: Date.now(),
|
|
338
|
+
};
|
|
339
|
+
if (!address) {
|
|
340
|
+
// structure that this function returns is complex and dynamic so i didnt want to hardcode it in EMPTY_SPARK_DATA
|
|
341
|
+
// This case only triggers if user doesnt have proxy and data is refetched once proxy is created
|
|
342
|
+
// TODO when refactoring spark figure out if this is the best solution.
|
|
343
|
+
payload.eModeCategories = sparkEmodeCategoriesMapping(extractedState, {});
|
|
344
|
+
|
|
345
|
+
return payload;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const loanInfoContract = SparkViewContractViem(provider, network);
|
|
349
|
+
const lendingPoolContract = createViemContractFromConfigFunc(market.lendingPool, market.lendingPoolAddress)(provider, network);
|
|
350
|
+
|
|
351
|
+
const marketAddress = market.providerAddress;
|
|
352
|
+
const _addresses = market.assets.map((a) => getAssetInfo(ethToWeth(a)).address);
|
|
353
|
+
|
|
354
|
+
const middleAddressIndex = Math.floor(_addresses.length / 2); // split addresses in half to avoid gas limit by multicall
|
|
355
|
+
|
|
356
|
+
const [userEMode, tokenBalances1, tokenBalances2] = await Promise.all([
|
|
357
|
+
lendingPoolContract.read.getUserEMode([address]),
|
|
358
|
+
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex) as EthAddress[]]),
|
|
359
|
+
loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length) as EthAddress[]]),
|
|
360
|
+
]);
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
const loanInfo = [...tokenBalances1, ...tokenBalances2];
|
|
364
|
+
|
|
365
|
+
const usedAssets = {} as SparkUsedAssets;
|
|
366
|
+
loanInfo.forEach((tokenInfo, i) => {
|
|
367
|
+
const asset = market.assets[i];
|
|
368
|
+
const isSupplied = tokenInfo.balance.toString() !== '0';
|
|
369
|
+
const isBorrowed = tokenInfo.borrowsStable.toString() !== '0' || tokenInfo.borrowsVariable.toString() !== '0';
|
|
370
|
+
if (!isSupplied && !isBorrowed) return;
|
|
371
|
+
|
|
372
|
+
const supplied = assetAmountInEth(tokenInfo.balance.toString(), asset);
|
|
373
|
+
const borrowedStable = assetAmountInEth(tokenInfo.borrowsStable.toString(), asset);
|
|
374
|
+
const borrowedVariable = assetAmountInEth(tokenInfo.borrowsVariable.toString(), asset);
|
|
375
|
+
const enabledAsCollateral = assetsData[asset].usageAsCollateralEnabled ? tokenInfo.enabledAsCollateral : false;
|
|
376
|
+
let interestMode;
|
|
377
|
+
if (borrowedVariable === '0' && borrowedStable !== '0') {
|
|
378
|
+
interestMode = '1';
|
|
379
|
+
} else if (borrowedVariable !== '0' && borrowedStable === '0') {
|
|
380
|
+
interestMode = '2';
|
|
381
|
+
} else {
|
|
382
|
+
interestMode = 'both';
|
|
383
|
+
}
|
|
384
|
+
if (!usedAssets[asset]) usedAssets[asset] = {} as SparkUsedAsset;
|
|
385
|
+
usedAssets[asset] = {
|
|
386
|
+
...usedAssets[asset],
|
|
387
|
+
symbol: asset,
|
|
388
|
+
supplied,
|
|
389
|
+
suppliedUsd: new Dec(supplied).mul(assetsData[asset].price).toString(),
|
|
390
|
+
isSupplied,
|
|
391
|
+
collateral: enabledAsCollateral,
|
|
392
|
+
stableBorrowRate: aprToApy(new Dec(tokenInfo.stableBorrowRate.toString()).div(1e25).toString()),
|
|
393
|
+
borrowedStable,
|
|
394
|
+
borrowedVariable,
|
|
395
|
+
borrowedUsdStable: new Dec(borrowedStable).mul(assetsData[asset].price).toString(),
|
|
396
|
+
borrowedUsdVariable: new Dec(borrowedVariable).mul(assetsData[asset].price).toString(),
|
|
397
|
+
borrowed: new Dec(borrowedStable).add(borrowedVariable).toString(),
|
|
398
|
+
borrowedUsd: new Dec(new Dec(borrowedVariable).add(borrowedStable)).mul(assetsData[asset].price).toString(),
|
|
399
|
+
isBorrowed,
|
|
400
|
+
eModeCategory: assetsData[asset].eModeCategory,
|
|
401
|
+
interestMode,
|
|
402
|
+
};
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
payload.eModeCategory = +userEMode.toString();
|
|
406
|
+
payload = {
|
|
407
|
+
...payload,
|
|
408
|
+
usedAssets,
|
|
409
|
+
...sparkGetAggregatedPositionData({
|
|
410
|
+
...extractedState, usedAssets, eModeCategory: payload.eModeCategory,
|
|
411
|
+
}),
|
|
412
|
+
};
|
|
413
|
+
payload.eModeCategories = sparkEmodeCategoriesMapping(extractedState, usedAssets);
|
|
414
|
+
payload.isInIsolationMode = sparkIsInIsolationMode({ usedAssets, assetsData });
|
|
415
|
+
payload.isInSiloedMode = sparkIsInIsolationMode({ usedAssets, assetsData });
|
|
416
|
+
|
|
417
|
+
payload.ratio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
418
|
+
? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
419
|
+
: '0';
|
|
420
|
+
payload.minRatio = '100';
|
|
421
|
+
payload.collRatio = payload.borrowedUsd && payload.borrowedUsd !== '0'
|
|
422
|
+
? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString()
|
|
423
|
+
: '0';
|
|
424
|
+
|
|
425
|
+
// Calculate borrow limits per asset
|
|
426
|
+
Object.values(payload.usedAssets).forEach((item) => {
|
|
427
|
+
if (item.isBorrowed) {
|
|
428
|
+
// eslint-disable-next-line no-param-reassign
|
|
429
|
+
item.stableLimit = calculateBorrowingAssetLimit(item.borrowedUsdStable, payload.borrowLimitUsd);
|
|
430
|
+
// eslint-disable-next-line no-param-reassign
|
|
431
|
+
item.variableLimit = calculateBorrowingAssetLimit(item.borrowedUsdVariable, payload.borrowLimitUsd);
|
|
432
|
+
// eslint-disable-next-line no-param-reassign
|
|
433
|
+
item.limit = calculateBorrowingAssetLimit(item.borrowedUsd, payload.borrowLimitUsd);
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
const { netApy, incentiveUsd, totalInterestUsd } = calculateNetApy({ usedAssets, assetsData });
|
|
438
|
+
payload.netApy = netApy;
|
|
439
|
+
payload.incentiveUsd = incentiveUsd;
|
|
440
|
+
payload.totalInterestUsd = totalInterestUsd;
|
|
441
|
+
|
|
442
|
+
return payload;
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
export const getSparkAccountData = async (
|
|
446
|
+
provider: EthereumProvider,
|
|
447
|
+
network: NetworkNumber,
|
|
448
|
+
address: EthAddress,
|
|
449
|
+
extractedState: { selectedMarket: SparkMarketData, assetsData: SparkAssetsData, eModeCategoriesData: EModeCategoriesData },
|
|
450
|
+
) => _getSparkAccountData(getViemProvider(provider, network), network, address, extractedState);
|
|
451
|
+
|
|
452
|
+
export const getSparkFullPositionData = async (provider: EthereumProvider, network: NetworkNumber, address: EthAddress, market: SparkMarketData): Promise<SparkPositionData> => {
|
|
453
|
+
const marketData = await getSparkMarketsData(provider, network, market);
|
|
454
|
+
const positionData = await getSparkAccountData(provider, network, address, { assetsData: marketData.assetsData, selectedMarket: market, eModeCategoriesData: marketData.eModeCategoriesData });
|
|
455
|
+
return positionData;
|
|
456
|
+
};
|