@defisaver/positions-sdk 2.1.160-shifter-v2-dev → 2.1.161-portfolio-api-dev

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.
Files changed (118) hide show
  1. package/cjs/aaveV2/index.js +0 -2
  2. package/cjs/curveUsd/index.d.ts +2 -5
  3. package/cjs/curveUsd/index.js +15 -30
  4. package/cjs/fluid/index.d.ts +0 -5
  5. package/cjs/fluid/index.js +1 -36
  6. package/cjs/helpers/aaveHelpers/index.js +0 -3
  7. package/cjs/helpers/aaveV4Helpers/index.js +0 -1
  8. package/cjs/helpers/compoundHelpers/index.js +0 -2
  9. package/cjs/helpers/curveUsdHelpers/index.d.ts +1 -3
  10. package/cjs/helpers/curveUsdHelpers/index.js +2 -16
  11. package/cjs/helpers/fluidHelpers/index.js +0 -1
  12. package/cjs/helpers/liquityV2Helpers/index.js +0 -1
  13. package/cjs/helpers/llamaLendHelpers/index.js +0 -2
  14. package/cjs/helpers/makerHelpers/index.d.ts +1 -1
  15. package/cjs/helpers/makerHelpers/index.js +2 -2
  16. package/cjs/helpers/morphoBlueHelpers/index.js +0 -2
  17. package/cjs/helpers/morphoMidnightHelpers/index.js +0 -2
  18. package/cjs/helpers/sparkHelpers/index.js +0 -1
  19. package/cjs/liquity/index.js +2 -16
  20. package/cjs/maker/index.d.ts +2 -7
  21. package/cjs/maker/index.js +12 -45
  22. package/cjs/markets/index.d.ts +0 -1
  23. package/cjs/markets/index.js +1 -3
  24. package/cjs/portfolio/index.d.ts +1 -5
  25. package/cjs/portfolio/index.js +7 -277
  26. package/cjs/staking/staking.d.ts +0 -20
  27. package/cjs/staking/staking.js +1 -19
  28. package/cjs/types/aave.d.ts +15 -4
  29. package/cjs/types/aaveV4.d.ts +0 -1
  30. package/cjs/types/compound.d.ts +26 -4
  31. package/cjs/types/curveUsd.d.ts +9 -7
  32. package/cjs/types/fluid.d.ts +0 -1
  33. package/cjs/types/liquity.d.ts +0 -4
  34. package/cjs/types/liquityV2.d.ts +0 -2
  35. package/cjs/types/llamaLend.d.ts +12 -1
  36. package/cjs/types/maker.d.ts +0 -4
  37. package/cjs/types/morphoBlue.d.ts +2 -2
  38. package/cjs/types/morphoMidnight.d.ts +0 -1
  39. package/cjs/types/portfolio.d.ts +10 -26
  40. package/cjs/types/spark.d.ts +21 -3
  41. package/esm/aaveV2/index.js +0 -2
  42. package/esm/curveUsd/index.d.ts +2 -5
  43. package/esm/curveUsd/index.js +15 -30
  44. package/esm/fluid/index.d.ts +0 -5
  45. package/esm/fluid/index.js +0 -33
  46. package/esm/helpers/aaveHelpers/index.js +0 -3
  47. package/esm/helpers/aaveV4Helpers/index.js +0 -1
  48. package/esm/helpers/compoundHelpers/index.js +0 -2
  49. package/esm/helpers/curveUsdHelpers/index.d.ts +1 -3
  50. package/esm/helpers/curveUsdHelpers/index.js +2 -16
  51. package/esm/helpers/fluidHelpers/index.js +0 -1
  52. package/esm/helpers/liquityV2Helpers/index.js +0 -1
  53. package/esm/helpers/llamaLendHelpers/index.js +0 -2
  54. package/esm/helpers/makerHelpers/index.d.ts +1 -1
  55. package/esm/helpers/makerHelpers/index.js +2 -2
  56. package/esm/helpers/morphoBlueHelpers/index.js +0 -2
  57. package/esm/helpers/morphoMidnightHelpers/index.js +0 -2
  58. package/esm/helpers/sparkHelpers/index.js +0 -1
  59. package/esm/liquity/index.js +2 -16
  60. package/esm/maker/index.d.ts +2 -7
  61. package/esm/maker/index.js +13 -44
  62. package/esm/markets/index.d.ts +0 -1
  63. package/esm/markets/index.js +0 -1
  64. package/esm/portfolio/index.d.ts +1 -5
  65. package/esm/portfolio/index.js +10 -279
  66. package/esm/staking/staking.d.ts +0 -20
  67. package/esm/staking/staking.js +0 -17
  68. package/esm/types/aave.d.ts +15 -4
  69. package/esm/types/aaveV4.d.ts +0 -1
  70. package/esm/types/compound.d.ts +26 -4
  71. package/esm/types/curveUsd.d.ts +9 -7
  72. package/esm/types/fluid.d.ts +0 -1
  73. package/esm/types/liquity.d.ts +0 -4
  74. package/esm/types/liquityV2.d.ts +0 -2
  75. package/esm/types/llamaLend.d.ts +12 -1
  76. package/esm/types/maker.d.ts +0 -4
  77. package/esm/types/morphoBlue.d.ts +2 -2
  78. package/esm/types/morphoMidnight.d.ts +0 -1
  79. package/esm/types/portfolio.d.ts +10 -26
  80. package/esm/types/spark.d.ts +21 -3
  81. package/package.json +1 -1
  82. package/src/aaveV2/index.ts +0 -2
  83. package/src/curveUsd/index.ts +16 -33
  84. package/src/fluid/index.ts +0 -40
  85. package/src/helpers/aaveHelpers/index.ts +0 -3
  86. package/src/helpers/aaveV4Helpers/index.ts +0 -1
  87. package/src/helpers/compoundHelpers/index.ts +0 -2
  88. package/src/helpers/curveUsdHelpers/index.ts +2 -23
  89. package/src/helpers/fluidHelpers/index.ts +0 -1
  90. package/src/helpers/liquityV2Helpers/index.ts +0 -1
  91. package/src/helpers/llamaLendHelpers/index.ts +0 -2
  92. package/src/helpers/makerHelpers/index.ts +1 -2
  93. package/src/helpers/morphoBlueHelpers/index.ts +0 -2
  94. package/src/helpers/morphoMidnightHelpers/index.ts +0 -2
  95. package/src/helpers/sparkHelpers/index.ts +0 -1
  96. package/src/liquity/index.ts +2 -17
  97. package/src/maker/index.ts +29 -77
  98. package/src/markets/index.ts +1 -2
  99. package/src/portfolio/index.ts +8 -261
  100. package/src/staking/staking.ts +0 -28
  101. package/src/types/aave.ts +18 -4
  102. package/src/types/aaveV4.ts +0 -1
  103. package/src/types/compound.ts +38 -4
  104. package/src/types/curveUsd.ts +17 -8
  105. package/src/types/fluid.ts +0 -1
  106. package/src/types/liquity.ts +0 -6
  107. package/src/types/liquityV2.ts +0 -2
  108. package/src/types/llamaLend.ts +19 -1
  109. package/src/types/maker.ts +0 -6
  110. package/src/types/morphoBlue.ts +3 -2
  111. package/src/types/morphoMidnight.ts +0 -1
  112. package/src/types/portfolio.ts +12 -31
  113. package/src/types/spark.ts +25 -3
  114. package/cjs/markets/maker/index.d.ts +0 -1
  115. package/cjs/markets/maker/index.js +0 -13
  116. package/esm/markets/maker/index.d.ts +0 -1
  117. package/esm/markets/maker/index.js +0 -10
  118. package/src/markets/maker/index.ts +0 -10
@@ -18,7 +18,6 @@ import { ZERO_ADDRESS } from '../constants';
18
18
  import { getViemProvider, setViemBlockNumber } from '../services/viem';
19
19
  import { getEthAmountForDecimals } from '../services/utils';
20
20
  import { getExposure } from '../moneymarket';
21
- import { calculateNetApyFromRates } from '../staking';
22
21
 
23
22
  export const LIQUITY_NORMAL_MODE_RATIO = 110; // MCR
24
23
  export const LIQUITY_RECOVERY_MODE_RATIO = 150; // CCR
@@ -90,15 +89,6 @@ export const _getLiquityTroveInfo = async (provider: Client, network: NetworkNum
90
89
  ]);
91
90
 
92
91
  const recoveryMode = troveInfo[6];
93
- const minCollateralRatio = recoveryMode ? LIQUITY_RECOVERY_MODE_RATIO : LIQUITY_NORMAL_MODE_RATIO;
94
- const collateral = assetAmountInEth(troveInfo[1].toString());
95
- const debtInAsset = assetAmountInEth(troveInfo[2].toString());
96
- const collateralUsd = new Dec(collateral).mul(assetAmountInEth(assetPrice.toString())).toString();
97
- const collRatio = +debtInAsset ? new Dec(collateralUsd).div(debtInAsset).mul(100).toString() : '0';
98
-
99
- // LUSD debt is interest free (only a one-off borrowing fee on issuance) and ETH collateral earns no yield,
100
- // so a trove's net APY is always 0. It is exposed for parity with the other protocols.
101
- const { netApy, totalInterestUsd, incentiveUsd } = calculateNetApyFromRates({ suppliedUsd: collateralUsd, borrowedUsd: debtInAsset });
102
92
 
103
93
  const payload = {
104
94
  troveStatus: LIQUITY_TROVE_STATUS_ENUM[+(troveInfo[0].toString())],
@@ -112,15 +102,10 @@ export const _getLiquityTroveInfo = async (provider: Client, network: NetworkNum
112
102
  totalETH: totalETH.toString(),
113
103
  totalLUSD: totalLUSD.toString(),
114
104
  debtInFront: debtInFront.toString(),
115
- minCollateralRatio,
116
- // Collateral ratio rebased so 100 sits on the trove's minimum collateral ratio (normalised safety ratio).
117
- safetyRatio: +minCollateralRatio > 0 ? new Dec(collRatio).div(minCollateralRatio).mul(100).toString() : '0',
105
+ minCollateralRatio: recoveryMode ? LIQUITY_RECOVERY_MODE_RATIO : LIQUITY_NORMAL_MODE_RATIO,
118
106
  priceForRecovery: new Dec(recoveryMode ? LIQUITY_RECOVERY_MODE_RATIO : LIQUITY_NORMAL_MODE_RATIO).mul(totalLUSD).div(totalETH).div(100)
119
107
  .toString(),
120
- exposure: getExposure(debtInAsset, collateralUsd),
121
- netApy,
122
- totalInterestUsd,
123
- incentiveUsd,
108
+ exposure: getExposure(assetAmountInEth(troveInfo[2].toString()), new Dec(assetAmountInEth(troveInfo[1].toString())).mul(assetPrice).toString()),
124
109
  };
125
110
 
126
111
  return payload;
@@ -1,22 +1,19 @@
1
1
  import Dec from 'decimal.js';
2
2
  import {
3
- assetAmountInEth, bytesToString, getAssetInfo, ilkToAsset, stringToBytes,
3
+ assetAmountInEth, bytesToString, getAssetInfo, ilkToAsset,
4
4
  } from '@defisaver/tokens';
5
5
  import { Client, PublicClient } from 'viem';
6
6
  import {
7
- Blockish, EthAddress, EthereumProvider, HexString, NetworkNumber, PositionBalances,
7
+ Blockish, EthAddress, EthereumProvider, NetworkNumber, PositionBalances,
8
8
  } from '../types/common';
9
9
  import {
10
10
  getConfigContractAddress, McdDogContractViem, McdGetCdpsContractViem, McdJugContractViem, McdSpotterContractViem, McdVatContractViem, McdViewContractViem,
11
11
  } from '../contracts';
12
- import {
13
- CdpData, CdpInfo, CdpType, IlkInfo,
14
- } from '../types';
12
+ import { CdpData, CdpInfo, CdpType } from '../types';
15
13
  import { wethToEth } from '../services/utils';
16
14
  import { parseCollateralInfo } from '../helpers/makerHelpers';
17
15
  import { getViemProvider, setViemBlockNumber } from '../services/viem';
18
16
  import { getExposure } from '../moneymarket';
19
- import { calculateNetApyFromRates, getStakingApy, STAKING_ASSETS } from '../staking';
20
17
 
21
18
  export const _getMakerAccountBalances = async (provider: PublicClient, network: NetworkNumber, block: Blockish, addressMapping: boolean, cdpId: string, _managerAddress?: EthAddress): Promise<PositionBalances> => {
22
19
  let balances: PositionBalances = {
@@ -51,7 +48,7 @@ export const _getMakerAccountBalances = async (provider: PublicClient, network:
51
48
  const [
52
49
  par,
53
50
  [_, mat],
54
- [artGlobal, rate, spot, line, dust],
51
+ [artGlobal, rate, spot, line],
55
52
  [duty],
56
53
  futureRate,
57
54
  chop,
@@ -72,7 +69,6 @@ export const _getMakerAccountBalances = async (provider: PublicClient, network:
72
69
  rate.toString(),
73
70
  spot.toString(),
74
71
  line.toString(),
75
- dust.toString(),
76
72
  duty.toString(),
77
73
  futureRate.toString(),
78
74
  chop.toString(),
@@ -133,73 +129,44 @@ export const getUserCdps = async (
133
129
  userAddress: EthAddress,
134
130
  ): Promise<CdpInfo[]> => _getUserCdps(getViemProvider(provider, network), network, userAddress);
135
131
 
136
- export const _getMakerIlksData = async (provider: Client, network: NetworkNumber, ilkLabels: string[]): Promise<Record<string, IlkInfo>> => {
132
+ export const _getMakerCdpData = async (provider: Client, network: NetworkNumber, cdp: CdpInfo): Promise<CdpData> => {
137
133
  const vatContract = McdVatContractViem(provider, network);
138
134
  const spotterContract = McdSpotterContractViem(provider, network);
139
135
  const dogContract = McdDogContractViem(provider, network);
140
136
  const jugContract = McdJugContractViem(provider, network);
141
137
 
142
- const par = await spotterContract.read.par();
143
-
144
- const ilksInfo = await Promise.all(ilkLabels.map(async (ilkLabel) => {
145
- const ilk = stringToBytes(ilkLabel) as HexString;
146
- const [
147
- [_, mat],
148
- [artGlobal, rate, spot, line, dust],
149
- [duty],
150
- futureRate,
151
- chop,
152
- ] = await Promise.all([
153
- spotterContract.read.ilks([ilk]),
154
- vatContract.read.ilks([ilk]),
155
- jugContract.read.ilks([ilk]),
156
- jugContract.read.drip([ilk]),
157
- dogContract.read.chop([ilk]),
158
- ]);
159
-
160
- return parseCollateralInfo(
161
- ilk,
162
- par.toString(),
163
- mat.toString(),
164
- artGlobal.toString(),
165
- rate.toString(),
166
- spot.toString(),
167
- line.toString(),
168
- dust.toString(),
169
- duty.toString(),
170
- futureRate.toString(),
171
- chop.toString(),
172
- );
173
- }));
174
-
175
- return Object.fromEntries(ilksInfo.map((ilkInfo) => [ilkInfo.ilkLabel, ilkInfo]));
176
- };
177
-
178
- export const getMakerIlksData = async (
179
- provider: EthereumProvider,
180
- network: NetworkNumber,
181
- ilkLabels: string[],
182
- ): Promise<Record<string, IlkInfo>> => _getMakerIlksData(getViemProvider(provider, network, { batch: { multicall: true } }), network, ilkLabels);
183
-
184
- /**
185
- * @param ilkInfo optional precomputed ilk data (from `_getMakerIlksData`); when provided the per-ilk reads are skipped
186
- */
187
- export const _getMakerCdpData = async (provider: Client, network: NetworkNumber, cdp: CdpInfo, ilkInfo?: IlkInfo): Promise<CdpData> => {
188
- const vatContract = McdVatContractViem(provider, network);
189
-
190
138
  const [
191
139
  [ink, art],
192
140
  coll,
193
- fetchedIlkInfo,
194
- collStakingApy,
141
+ par,
142
+ [_, mat],
143
+ [artGlobal, rate, spot, line],
144
+ [duty],
145
+ futureRate,
146
+ chop,
195
147
  ] = await Promise.all([
196
148
  vatContract.read.urns([cdp.ilk, cdp.urn]),
197
149
  vatContract.read.gem([cdp.ilk, cdp.urn]),
198
- ilkInfo || _getMakerIlksData(provider, network, [cdp.ilkLabel]).then((ilks) => ilks[cdp.ilkLabel]),
199
- STAKING_ASSETS.includes(cdp.asset) ? getStakingApy(cdp.asset) : Promise.resolve('0'),
150
+ spotterContract.read.par(),
151
+ spotterContract.read.ilks([cdp.ilk]),
152
+ vatContract.read.ilks([cdp.ilk]),
153
+ jugContract.read.ilks([cdp.ilk]),
154
+ jugContract.read.drip([cdp.ilk]),
155
+ dogContract.read.chop([cdp.ilk]),
200
156
  ]);
201
157
 
202
- const collInfo = fetchedIlkInfo;
158
+ const collInfo = parseCollateralInfo(
159
+ cdp.ilk,
160
+ par.toString(),
161
+ mat.toString(),
162
+ artGlobal.toString(),
163
+ rate.toString(),
164
+ spot.toString(),
165
+ line.toString(),
166
+ duty.toString(),
167
+ futureRate.toString(),
168
+ chop.toString(),
169
+ );
203
170
 
204
171
  const collateral = assetAmountInEth(ink.toString(), `MCD-${cdp.asset}`);
205
172
 
@@ -213,20 +180,9 @@ export const _getMakerCdpData = async (provider: Client, network: NetworkNumber,
213
180
  let ratio = new Dec(ink).times(collInfo.assetPrice).div(debt).times(100)
214
181
  .toString();
215
182
  if (new Dec(debt).eq(0)) ratio = '0';
216
- // Collateral ratio rebased so 100 sits on the ilk's liquidation ratio (normalised safety ratio).
217
- const safetyRatio = +collInfo.liqPercent > 0 ? new Dec(ratio).div(collInfo.liqPercent).mul(100).toString() : '0';
218
183
 
219
184
  const debtTooLow = new Dec(debt).gt(0) && new Dec(assetAmountInEth(debt, 'DAI')).lt(collInfo.minDebt);
220
185
 
221
- // DAI debt accrues the ilk's stability fee. Collateral earns nothing inside the vault, except for the
222
- // native yield of staked collateral (e.g. wstETH), which is tracked as an incentive.
223
- const { netApy, totalInterestUsd, incentiveUsd } = calculateNetApyFromRates({
224
- suppliedUsd: collateralUsd,
225
- borrowedUsd: assetAmountInEth(debt, 'DAI'),
226
- borrowRate: collInfo.stabilityFee.toString(),
227
- incentives: [{ apy: collStakingApy, amountUsd: collateralUsd }],
228
- });
229
-
230
186
  return {
231
187
  owner: cdp.owner,
232
188
  id: cdp.id.toString(),
@@ -245,7 +201,6 @@ export const _getMakerCdpData = async (provider: Client, network: NetworkNumber,
245
201
  debtAssetMarketPrice: '1',
246
202
  liquidationPrice,
247
203
  ratio,
248
- safetyRatio,
249
204
  liqRatio: collInfo.liqRatio.toString(),
250
205
  liqPercent: parseFloat(collInfo.liqPercent.toString()),
251
206
  assetPrice: collInfo.assetPrice,
@@ -261,9 +216,6 @@ export const _getMakerCdpData = async (provider: Client, network: NetworkNumber,
261
216
  liquidationFee: collInfo.liquidationFee,
262
217
  lastUpdated: Date.now(),
263
218
  exposure: getExposure(assetAmountInEth(debt, 'DAI'), collateralUsd),
264
- netApy,
265
- totalInterestUsd,
266
- incentiveUsd,
267
219
  };
268
220
  };
269
221
 
@@ -30,5 +30,4 @@ export {
30
30
  getFTokenAddress,
31
31
  getFluidMarketInfoByAddress,
32
32
  } from './fluid';
33
- export { AaveV4Spokes, findAaveV4SpokeByAddress } from './aaveV4';
34
- export { MakerActiveIlks } from './maker';
33
+ export { AaveV4Spokes, findAaveV4SpokeByAddress } from './aaveV4';
@@ -7,7 +7,6 @@ import {
7
7
  CrvUsdMarkets,
8
8
  LiquityV2Markets,
9
9
  LlamaLendMarkets,
10
- MakerActiveIlks,
11
10
  MorphoBlueMarkets,
12
11
  MorphoMidnightMarkets,
13
12
  SparkMarkets,
@@ -28,7 +27,6 @@ import {
28
27
  LlamaLendGlobalMarketData,
29
28
  MorphoBlueMarketInfo,
30
29
  MorphoMidnightMarketInfo,
31
- PortfolioMarketsData,
32
30
  PortfolioPositionsData,
33
31
  SparkMarketsData,
34
32
  } from '../types';
@@ -38,13 +36,13 @@ import { _getCurveUsdGlobalData, _getCurveUsdUserData } from '../curveUsd';
38
36
  import { _getLlamaLendGlobalData, _getLlamaLendUserData } from '../llamaLend';
39
37
  import { _getAaveV3AccountData, _getAaveV3MarketData, getStakeAaveData } from '../aaveV3';
40
38
  import { ZERO_ADDRESS } from '../constants';
41
- import { _getMakerCdpData, _getMakerIlksData, _getUserCdps } from '../maker';
39
+ import { _getMakerCdpData, _getUserCdps } from '../maker';
42
40
  import { _getAaveV2AccountData, _getAaveV2MarketsData } from '../aaveV2';
43
41
  import { _getCompoundV2AccountData, _getCompoundV2MarketsData } from '../compoundV2';
44
42
  import { getViemProvider } from '../services/viem';
45
43
  import { _getLiquityTroveInfo, getLiquityStakingData } from '../liquity';
46
44
  import { _getLiquityV2MarketData, getLiquitySAndYBold, getLiquityV2Staking } from '../liquityV2';
47
- import { _getAllFluidMarketDataPortfolio, _getAllUserEarnPositionsWithFTokens, _getUserPositionsPortfolio } from '../fluid';
45
+ import { _getAllUserEarnPositionsWithFTokens, _getUserPositionsPortfolio } from '../fluid';
48
46
  import { getUmbrellaData } from '../umbrella';
49
47
  import { getMerklUnclaimedRewards, getUnclaimedRewardsForAllMarkets } from '../claiming/aaveV3';
50
48
  import { fetchSparkAirdropRewards, fetchSparkRewards } from '../claiming/spark';
@@ -508,7 +506,9 @@ export async function getPortfolioData(provider: EthereumProvider, network: Netw
508
506
  positions[address.toLowerCase() as EthAddress].spark[market.value] = { error: `Error fetching Spark account data for address ${address} on market ${market.value}`, data: null };
509
507
  }
510
508
  })).flat(),
511
- ...addresses.map(async (address) => makerCdps[address.toLowerCase() as EthAddress]?.map(async (cdpInfo) => {
509
+ // flatMap, not map: each CDP's fetch has to be one of the awaited promises, or getPortfolioData can return
510
+ // before a vault's data lands and the vault is missing from the result.
511
+ ...addresses.flatMap((address) => (makerCdps[address.toLowerCase() as EthAddress] ?? []).map(async (cdpInfo) => {
512
512
  try {
513
513
  const cdpData = await _getMakerCdpData(client, network, cdpInfo);
514
514
  if (cdpData) {
@@ -518,7 +518,7 @@ export async function getPortfolioData(provider: EthereumProvider, network: Netw
518
518
  console.error(`Error fetching Maker CDP data for address ${address} with ID ${cdpInfo.id}:`, error);
519
519
  positions[address.toLowerCase() as EthAddress].maker[cdpInfo.id] = { error: `Error fetching Maker CDP data for address ${address} with ID ${cdpInfo.id}`, data: null };
520
520
  }
521
- })).flat(),
521
+ })),
522
522
  ...aaveV2Markets.map((market) => addresses.map(async (address) => {
523
523
  try {
524
524
  const accData = await _getAaveV2AccountData(client, network, address, aaveV2MarketsData[market.value].assetsData, market);
@@ -549,9 +549,9 @@ export async function getPortfolioData(provider: EthereumProvider, network: Netw
549
549
  }),
550
550
  ...crvUsdMarkets.map((market) => addresses.map(async (address) => {
551
551
  try {
552
- const accData = await _getCurveUsdUserData(client, network, address, market, crvUsdMarketsData[market.value].activeBand, crvUsdMarketsData[market.value].borrowRate);
552
+ const accData = await _getCurveUsdUserData(client, network, address, market, crvUsdMarketsData[market.value].activeBand);
553
553
  if (new Dec(accData.suppliedUsd).gt(0) || new Dec(accData.borrowedUsd).gt(0)) {
554
- positions[address.toLowerCase() as EthAddress].crvUsd[market.value] = { error: '', data: accData };
554
+ positions[address.toLowerCase() as EthAddress].crvUsd[market.value] = { error: '', data: { ...accData, borrowRate: crvUsdMarketsData[market.value].borrowRate } };
555
555
  }
556
556
  } catch (error) {
557
557
  console.error(`Error fetching Curve USD account data for address ${address} on market ${market.value}:`, error);
@@ -593,257 +593,4 @@ export async function getPortfolioData(provider: EthereumProvider, network: Netw
593
593
  };
594
594
  }
595
595
 
596
-
597
- export async function getShifterPortfolioData(provider: EthereumProvider, network: NetworkNumber, defaultProvider: EthereumProvider, addresses: EthAddress[], isSim = false): Promise<{
598
- positions: PortfolioPositionsData;
599
- markets: PortfolioMarketsData;
600
- }> {
601
- const isMainnet = network === NetworkNumber.Eth;
602
- const isFluidSupported = [NetworkNumber.Eth, NetworkNumber.Arb, NetworkNumber.Base, NetworkNumber.Plasma].includes(network);
603
-
604
- const morphoMarkets = Object.values(MorphoBlueMarkets(network)).filter((market) => market.chainIds.includes(network));
605
- const compoundV3Markets = Object.values(CompoundMarkets(network)).filter((market) => market.chainIds.includes(network) && market.value !== CompoundVersions.CompoundV2);
606
- const sparkMarkets = Object.values(SparkMarkets(network)).filter((market) => market.chainIds.includes(network));
607
- const aaveV3Markets = [AaveVersions.AaveV3, AaveVersions.AaveV3Lido, AaveVersions.AaveV3Etherfi].map((version) => AaveMarkets(network)[version]).filter((market) => market.chainIds.includes(network));
608
- const aaveV2Markets = [AaveVersions.AaveV2].map((version) => AaveMarkets(network)[version]).filter((market) => market.chainIds.includes(network));
609
- const compoundV2Markets = [CompoundVersions.CompoundV2].map((version) => CompoundMarkets(network)[version]).filter((market) => market.chainIds.includes(network));
610
- const crvUsdMarkets = Object.values(CrvUsdMarkets(network)).filter((market) => market.chainIds.includes(network));
611
- const llamaLendMarkets = [NetworkNumber.Eth, NetworkNumber.Arb].includes(network) ? Object.values(LlamaLendMarkets(network)).filter((market) => market.chainIds.includes(network)) : [];
612
- const liquityV2Markets = [NetworkNumber.Eth].includes(network) ? Object.values(LiquityV2Markets(network)) : [];
613
- const aaveV4Spokes = Object.values(AaveV4Spokes(network)).filter((market) => market.chainIds.includes(network));
614
-
615
- const args: [NetworkNumber, any?] = [network, { batch: { multicall: { batchSize: isSim ? 2_000 : 2_500_000 } } }];
616
- const client = getViemProvider(provider, ...args);
617
- const defaultClient = getViemProvider(defaultProvider, ...args);
618
-
619
- const markets: PortfolioMarketsData = {
620
- morphoMarketsData: {},
621
- morphoMidnightMarketsData: {}, // Morpho Midnight is not fetched for the shifter; key kept so the payload shape is stable
622
- compoundV3MarketsData: {},
623
- sparkMarketsData: {},
624
- aaveV3MarketsData: {},
625
- aaveV2MarketsData: {},
626
- compoundV2MarketsData: {},
627
- crvUsdMarketsData: {},
628
- llamaLendMarketsData: {},
629
- liquityV2MarketsData: {},
630
- aaveV4SpokesData: {},
631
- fluidMarketsData: {},
632
- makerMarketsData: {},
633
- };
634
- const makerCdps: Record<string, CdpInfo[]> = {};
635
-
636
- const positions: PortfolioPositionsData = {};
637
-
638
- for (const address of addresses) {
639
- positions[address.toLowerCase() as EthAddress] = {
640
- aaveV3: {},
641
- aaveV4: {},
642
- morphoBlue: {},
643
- morphoMidnight: {}, // not fetched for the shifter (see markets above)
644
- compoundV3: {},
645
- spark: {},
646
- maker: {},
647
- aaveV2: {},
648
- compoundV2: {},
649
- liquity: {},
650
- crvUsd: {},
651
- llamaLend: {},
652
- fluid: {
653
- error: '',
654
- data: {},
655
- },
656
- };
657
- }
658
-
659
- await Promise.allSettled([
660
- // === MARKET DATA (needs to be fetched first) ===
661
- ...morphoMarkets.map(async (market) => {
662
- markets.morphoMarketsData[market.value] = await _getMorphoBluePortfolioMarketData(client, network, market);
663
- }),
664
- ...compoundV3Markets.map(async (market) => {
665
- markets.compoundV3MarketsData[market.value] = await _getCompoundV3MarketsData(client, network, market, defaultClient);
666
- }),
667
- ...sparkMarkets.map(async (market) => {
668
- markets.sparkMarketsData[market.value] = await _getSparkMarketsData(client, network, market);
669
- }),
670
- ...aaveV3Markets.map(async (market) => {
671
- markets.aaveV3MarketsData[market.value] = await _getAaveV3MarketData(client, network, market);
672
- }),
673
- ...aaveV4Spokes.map(async (spoke) => {
674
- markets.aaveV4SpokesData[spoke.value] = await _getAaveV4SpokeData(client, network, spoke);
675
- }),
676
- ...aaveV2Markets.map(async (market) => {
677
- markets.aaveV2MarketsData[market.value] = await _getAaveV2MarketsData(client, network, market);
678
- }),
679
- ...compoundV2Markets.map(async (market) => {
680
- markets.compoundV2MarketsData[market.value] = await _getCompoundV2MarketsData(client, network);
681
- }),
682
- ...crvUsdMarkets.map(async (market) => {
683
- markets.crvUsdMarketsData[market.value] = await _getCurveUsdGlobalData(client, network, market);
684
- }),
685
- ...llamaLendMarkets.map(async (market) => {
686
- markets.llamaLendMarketsData[market.value] = await _getLlamaLendGlobalData(client, network, market);
687
- }),
688
- ...liquityV2Markets.map(async (market) => {
689
- markets.liquityV2MarketsData[market.value] = await _getLiquityV2MarketData(client, network, market);
690
- }),
691
- (async () => {
692
- if (!isFluidSupported) return;
693
- try {
694
- markets.fluidMarketsData = await _getAllFluidMarketDataPortfolio(client, network);
695
- } catch (error) {
696
- console.error('Error fetching Fluid markets data:', error);
697
- }
698
- })(),
699
- (async () => {
700
- if (!isMainnet) return; // Maker CDPs are only available on mainnet
701
- try {
702
- markets.makerMarketsData = await _getMakerIlksData(client, network, MakerActiveIlks);
703
- } catch (error) {
704
- console.error('Error fetching Maker ilks data:', error);
705
- }
706
- })(),
707
-
708
- // === INDEPENDENT USER DATA (doesn't depend on market data) ===
709
- ...addresses.map(async (address) => {
710
- if (!isMainnet) return; // Maker CDPs are only available on mainnet
711
- const makerCdp = await _getUserCdps(client, network, address);
712
- makerCdps[address.toLowerCase() as EthAddress] = makerCdp;
713
- }),
714
- ...addresses.map(async (address) => {
715
- try {
716
- if (!isFluidSupported) return; // Fluid is not available on Optimism
717
- const userPositions = (await _getUserPositionsPortfolio(client, network, address));
718
- for (const position of userPositions) {
719
- if (position.userData && new Dec(position.userData.suppliedUsd).gt(0)) {
720
- positions[address.toLowerCase() as EthAddress].fluid.data[position.userData.nftId] = position.userData;
721
- }
722
- }
723
- } catch (error) {
724
- console.error(`Error fetching Fluid positions for address ${address}:`, error);
725
- positions[address.toLowerCase() as EthAddress].fluid = {
726
- error: `Error fetching Fluid positions for address ${address}`,
727
- data: {},
728
- };
729
- }
730
- }),
731
- ]);
732
-
733
- await Promise.all([
734
- ...aaveV3Markets.map((market) => addresses.map(async (address) => {
735
- try {
736
- const accData = await _getAaveV3AccountData(client, network, address, { selectedMarket: market, ...markets.aaveV3MarketsData[market.value] });
737
- if (new Dec(accData.suppliedUsd).gt(0)) positions[address.toLowerCase() as EthAddress].aaveV3[market.value] = { error: '', data: accData };
738
- } catch (error) {
739
- console.error(`Error fetching AaveV3 account data for address ${address} on market ${market.value}:`, error);
740
- positions[address.toLowerCase() as EthAddress].aaveV3[market.value] = { error: `Error fetching AaveV3 account data for address ${address} on market ${market.value}`, data: null };
741
- }
742
- })).flat(),
743
- ...aaveV4Spokes.map((spoke) => addresses.map(async (address) => {
744
- try {
745
- const accData = await _getAaveV4AccountData(client, network, markets.aaveV4SpokesData[spoke.value], address);
746
- if (new Dec(accData.suppliedUsd).gt(0)) positions[address.toLowerCase() as EthAddress].aaveV4[spoke.value] = { error: '', data: accData };
747
- } catch (error) {
748
- console.error(`Error fetching AaveV4 account data for address ${address} on spoke ${spoke.value}:`, error);
749
- positions[address.toLowerCase() as EthAddress].aaveV4[spoke.value] = { error: `Error fetching AaveV4 account data for address ${address} on spoke ${spoke.value}`, data: null };
750
- }
751
- })).flat(),
752
- ...morphoMarkets.map((market) => addresses.map(async (address) => {
753
- try {
754
- const accData = await _getMorphoBlueAccountData(client, network, address, market, markets.morphoMarketsData[market.value]);
755
- if (new Dec(accData.suppliedUsd).gt(0)) positions[address.toLowerCase() as EthAddress].morphoBlue[market.value] = { error: '', data: accData };
756
- } catch (error) {
757
- console.error(`Error fetching MorphoBlue account data for address ${address} on market ${market.value}:`, error);
758
- positions[address.toLowerCase() as EthAddress].morphoBlue[market.value] = { error: `Error fetching MorphoBlue account data for address ${address} on market ${market.value}`, data: null };
759
- }
760
- })).flat(),
761
- ...compoundV3Markets.map((market) => addresses.map(async (address) => {
762
- try {
763
- const accData = await _getCompoundV3AccountData(client, network, address, ZERO_ADDRESS, { selectedMarket: market, assetsData: markets.compoundV3MarketsData[market.value].assetsData });
764
- if (new Dec(accData.suppliedUsd).gt(0)) positions[address.toLowerCase() as EthAddress].compoundV3[market.value] = { error: '', data: accData };
765
- } catch (error) {
766
- console.error(`Error fetching CompoundV3 account data for address ${address} on market ${market.value}:`, error);
767
- positions[address.toLowerCase() as EthAddress].compoundV3[market.value] = { error: `Error fetching CompoundV3 account data for address ${address} on market ${market.value}`, data: null };
768
- }
769
- })).flat(),
770
- ...sparkMarkets.map((market) => addresses.map(async (address) => {
771
- try {
772
- const accData = await _getSparkAccountData(client, network, address, { selectedMarket: market, assetsData: markets.sparkMarketsData[market.value].assetsData, eModeCategoriesData: markets.sparkMarketsData[market.value].eModeCategoriesData });
773
- if (new Dec(accData.suppliedUsd).gt(0)) positions[address.toLowerCase() as EthAddress].spark[market.value] = { error: '', data: accData };
774
- } catch (error) {
775
- console.error(`Error fetching Spark account data for address ${address} on market ${market.value}:`, error);
776
- positions[address.toLowerCase() as EthAddress].spark[market.value] = { error: `Error fetching Spark account data for address ${address} on market ${market.value}`, data: null };
777
- }
778
- })).flat(),
779
- ...addresses.map(async (address) => makerCdps[address.toLowerCase() as EthAddress]?.map(async (cdpInfo) => {
780
- try {
781
- // reuse ilk data fetched for the markets payload; ilks outside the active set are fetched on demand
782
- const cdpData = await _getMakerCdpData(client, network, cdpInfo, markets.makerMarketsData[cdpInfo.ilkLabel]);
783
- if (cdpData) {
784
- positions[address.toLowerCase() as EthAddress].maker[cdpInfo.id] = { error: '', data: cdpData };
785
- }
786
- } catch (error) {
787
- console.error(`Error fetching Maker CDP data for address ${address} with ID ${cdpInfo.id}:`, error);
788
- positions[address.toLowerCase() as EthAddress].maker[cdpInfo.id] = { error: `Error fetching Maker CDP data for address ${address} with ID ${cdpInfo.id}`, data: null };
789
- }
790
- })).flat(),
791
- ...aaveV2Markets.map((market) => addresses.map(async (address) => {
792
- try {
793
- const accData = await _getAaveV2AccountData(client, network, address, markets.aaveV2MarketsData[market.value].assetsData, market);
794
- if (new Dec(accData.suppliedUsd).gt(0)) positions[address.toLowerCase() as EthAddress].aaveV2[market.value] = { error: '', data: accData };
795
- } catch (error) {
796
- console.error(`Error fetching AaveV2 account data for address ${address}:`, error);
797
- positions[address.toLowerCase() as EthAddress].aaveV2[market.value] = { error: `Error fetching AaveV2 account data for address ${address}`, data: null };
798
- }
799
- })).flat(),
800
- ...compoundV2Markets.map((market) => addresses.map(async (address) => {
801
- try {
802
- const accData = await _getCompoundV2AccountData(client, network, address, markets.compoundV2MarketsData[market.value].assetsData);
803
- if (new Dec(accData.suppliedUsd).gt(0)) positions[address.toLowerCase() as EthAddress].compoundV2[market.value] = { error: '', data: accData };
804
- } catch (error) {
805
- console.error(`Error fetching CompoundV2 account data for address ${address}:`, error);
806
- positions[address.toLowerCase() as EthAddress].compoundV2[market.value] = { error: `Error fetching CompoundV2 account data for address ${address}`, data: null };
807
- }
808
- })).flat(),
809
- ...addresses.map(async (address) => {
810
- try {
811
- if (!isMainnet) return; // Liquity trove info is only available on mainnet
812
- const troveInfo = await _getLiquityTroveInfo(client, network, address);
813
- if (new Dec(troveInfo.collateral).gt(0)) positions[address.toLowerCase() as EthAddress].liquity = { error: '', data: troveInfo };
814
- } catch (error) {
815
- console.error(`Error fetching Liquity trove info for address ${address}:`, error);
816
- positions[address.toLowerCase() as EthAddress].liquity = { error: `Error fetching Liquity trove info for address ${address}`, data: null };
817
- }
818
- }),
819
- ...crvUsdMarkets.map((market) => addresses.map(async (address) => {
820
- try {
821
- const accData = await _getCurveUsdUserData(client, network, address, market, markets.crvUsdMarketsData[market.value].activeBand, markets.crvUsdMarketsData[market.value].borrowRate);
822
- if (new Dec(accData.suppliedUsd).gt(0) || new Dec(accData.borrowedUsd).gt(0)) {
823
- positions[address.toLowerCase() as EthAddress].crvUsd[market.value] = { error: '', data: accData };
824
- }
825
- } catch (error) {
826
- console.error(`Error fetching Curve USD account data for address ${address} on market ${market.value}:`, error);
827
- positions[address.toLowerCase() as EthAddress].crvUsd[market.value] = { error: `Error fetching Curve USD account data for address ${address} on market ${market.value}`, data: null };
828
- }
829
- })).flat(),
830
- ...llamaLendMarkets.map((market) => addresses.map(async (address) => {
831
- try {
832
- const accData = await _getLlamaLendUserData(client, network, address, market, markets.llamaLendMarketsData[market.value]);
833
- if (new Dec(accData.suppliedUsd).gt(0) || new Dec(accData.borrowedUsd).gt(0)) {
834
- positions[address.toLowerCase() as EthAddress].llamaLend[market.value] = { error: '', data: { ...accData, borrowRate: markets.llamaLendMarketsData[market.value].borrowRate } };
835
- }
836
- } catch (error) {
837
- console.error(`Error fetching LlamaLend account data for address ${address} on market ${market.value}:`, error);
838
- positions[address.toLowerCase() as EthAddress].llamaLend[market.value] = { error: `Error fetching LlamaLend account data for address ${address} on market ${market.value}`, data: null };
839
- }
840
- })).flat(),
841
- ]);
842
-
843
- return {
844
- positions,
845
- markets,
846
- };
847
- }
848
-
849
596
  export * from './discovery';
@@ -137,34 +137,6 @@ export const calculateInterestEarned = (principal: string, interest: string, typ
137
137
  return (+principal * (((1 + (+interest / 100) / BLOCKS_IN_A_YEAR)) ** (BLOCKS_IN_A_YEAR * interval))) - +principal; // eslint-disable-line
138
138
  };
139
139
 
140
- /**
141
- * Net APY for positions that have a single known borrow rate (and optionally a single supply rate)
142
- * instead of per-asset `assetsData` to feed into `calculateNetApy` (Maker, crvUSD, Liquity v1).
143
- * All rates are yearly percentages that are already compounded. `incentives` are extra yields
144
- * (e.g. the native staking yield of the collateral) applied to their own USD base and summed into `incentiveUsd`.
145
- */
146
- export const calculateNetApyFromRates = ({
147
- suppliedUsd, borrowedUsd, supplyRate = '0', borrowRate = '0', incentives = [],
148
- }: {
149
- suppliedUsd: string,
150
- borrowedUsd: string,
151
- supplyRate?: string,
152
- borrowRate?: string,
153
- incentives?: { apy: string, amountUsd: string }[],
154
- }) => {
155
- const supplyInterest = new Dec(calculateInterestEarned(suppliedUsd, supplyRate, 'year', true));
156
- const borrowInterest = new Dec(calculateInterestEarned(borrowedUsd, borrowRate, 'year', true));
157
- const incentiveUsd = incentives
158
- .reduce((acc, { apy, amountUsd }) => acc.add(calculateInterestEarned(amountUsd, apy, 'year', true)), new Dec(0))
159
- .toString();
160
-
161
- const totalInterestUsd = supplyInterest.sub(borrowInterest).add(incentiveUsd).toString();
162
- const balance = new Dec(suppliedUsd).sub(borrowedUsd);
163
- const netApy = balance.isZero() ? '0' : new Dec(totalInterestUsd).div(balance).times(100).toString();
164
-
165
- return { netApy, totalInterestUsd, incentiveUsd };
166
- };
167
-
168
140
  export const calculateNetApy = ({
169
141
  usedAssets, assetsData, optionalData,
170
142
  }: { usedAssets: MMUsedAssets, assetsData: MMAssetsData, optionalData?: any }) => {
package/src/types/aave.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ EthAddress,
2
3
  IncentiveData,
3
4
  LeverageType,
4
5
  MMAssetData, MMPositionData, MMUsedAsset, NetworkNumber,
@@ -96,6 +97,9 @@ export interface AaveV3AssetData extends AaveAssetData {
96
97
  liquidationBonus: string,
97
98
  supplyIncentives: IncentiveData[];
98
99
  borrowIncentives: IncentiveData[];
100
+ // Set by _getAaveV3MarketData. Optional, so objects built by hand still type-check.
101
+ aTokenAddress?: EthAddress,
102
+ vTokenAddress?: EthAddress,
99
103
  }
100
104
 
101
105
  export type EModeCategoriesData = Record<number, EModeCategoryData>;
@@ -137,14 +141,20 @@ export type AaveV2UsedAssets = AaveUsedAssets<AaveV2UsedAsset>;
137
141
 
138
142
  export type AaveV3UsedAssets = AaveUsedAssets<AaveV3UsedAsset>;
139
143
 
140
- export interface AavePositionData extends MMPositionData {
144
+ /**
145
+ * Fields aaveAnyGetAggregatedPositionData adds to every Aave V2/V3 position at runtime, on top of those declared
146
+ * below. Optional, so code that builds a position by hand keeps compiling.
147
+ */
148
+ export type AavePositionAggregatedFields = Partial<Omit<AaveV3AggregatedPositionData,
149
+ | keyof MMPositionData | 'ratio' | 'collRatio' | 'safetyRatioWithLtvZeroFallback' | 'suppliedUsd' | 'borrowedUsd'
150
+ | 'borrowLimitUsd' | 'suppliedCollateralUsd' | 'incentiveUsd' | 'totalInterestUsd'>>;
151
+
152
+ export interface AavePositionData extends MMPositionData, AavePositionAggregatedFields {
141
153
  ratio: string,
142
154
  minRatio: string,
143
155
  collRatio: string,
144
156
  // Safety ratio as evaluated by automation bots (LTV-0 collateral credited at LLTV - 5%). Aave v3 only.
145
157
  safetyRatioWithLtvZeroFallback?: string,
146
- // Normalised safety ratio (100 = liquidation on every protocol). Aave v3: the LTV-0 fallback ratio, Aave v2: `ratio`.
147
- safetyRatio?: string,
148
158
  suppliedUsd: string,
149
159
  borrowedUsd: string,
150
160
  borrowLimitUsd: string,
@@ -158,6 +168,11 @@ export interface AavePositionData extends MMPositionData {
158
168
 
159
169
  export interface AaveV2PositionData extends AavePositionData {
160
170
  usedAssets: AaveV2UsedAssets,
171
+ // Always their empty values: _getAaveV2AccountData starts from Aave V3's EMPTY_AAVE_DATA, which carries them.
172
+ eModeCategory?: number,
173
+ isInIsolationMode?: boolean,
174
+ isInSiloedMode?: boolean,
175
+ eModeCategories?: { [key: number]: EModeCategoryDataMapping },
161
176
  }
162
177
 
163
178
  export interface AaveV3PositionData extends AavePositionData {
@@ -179,7 +194,6 @@ export interface AaveV3AggregatedPositionData {
179
194
  collRatio: string,
180
195
  borrowLimitWithLtvZeroFallbackUsd: string,
181
196
  safetyRatioWithLtvZeroFallback: string,
182
- safetyRatio: string,
183
197
  netApy: string,
184
198
  incentiveUsd: string,
185
199
  totalInterestUsd: string,
@@ -183,7 +183,6 @@ export interface AaveV4AggregatedPositionData {
183
183
  leftToBorrowUsd: string,
184
184
  ratio: string,
185
185
  collRatio: string,
186
- safetyRatio: string,
187
186
  liqRatio: string,
188
187
  liqPercent: string,
189
188
  leveragedType: LeverageType,