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