@defisaver/positions-sdk 2.0.12 → 2.0.14

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 (74) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +64 -64
  4. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  5. package/cjs/markets/aave/marketAssets.js +1 -1
  6. package/cjs/staking/staking.js +3 -1
  7. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  8. package/esm/markets/aave/marketAssets.js +1 -1
  9. package/esm/staking/staking.js +3 -1
  10. package/package.json +47 -47
  11. package/src/aaveV2/index.ts +236 -236
  12. package/src/aaveV3/index.ts +488 -488
  13. package/src/compoundV2/index.ts +240 -240
  14. package/src/compoundV3/index.ts +270 -270
  15. package/src/config/contracts.ts +1107 -1107
  16. package/src/constants/index.ts +6 -6
  17. package/src/contracts.ts +107 -107
  18. package/src/curveUsd/index.ts +250 -250
  19. package/src/eulerV2/index.ts +314 -314
  20. package/src/exchange/index.ts +25 -25
  21. package/src/fluid/index.ts +1568 -1568
  22. package/src/helpers/aaveHelpers/index.ts +170 -170
  23. package/src/helpers/compoundHelpers/index.ts +261 -261
  24. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  25. package/src/helpers/eulerHelpers/index.ts +259 -259
  26. package/src/helpers/fluidHelpers/index.ts +324 -324
  27. package/src/helpers/index.ts +10 -10
  28. package/src/helpers/liquityV2Helpers/index.ts +80 -80
  29. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  30. package/src/helpers/makerHelpers/index.ts +52 -52
  31. package/src/helpers/morphoBlueHelpers/index.ts +390 -390
  32. package/src/helpers/sparkHelpers/index.ts +155 -155
  33. package/src/index.ts +45 -45
  34. package/src/liquity/index.ts +104 -104
  35. package/src/liquityV2/index.ts +408 -408
  36. package/src/llamaLend/index.ts +296 -296
  37. package/src/maker/index.ts +223 -223
  38. package/src/markets/aave/index.ts +116 -116
  39. package/src/markets/aave/marketAssets.ts +49 -49
  40. package/src/markets/compound/index.ts +227 -227
  41. package/src/markets/compound/marketsAssets.ts +90 -90
  42. package/src/markets/curveUsd/index.ts +69 -69
  43. package/src/markets/euler/index.ts +26 -26
  44. package/src/markets/fluid/index.ts +2456 -2456
  45. package/src/markets/index.ts +25 -25
  46. package/src/markets/liquityV2/index.ts +102 -102
  47. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  48. package/src/markets/llamaLend/index.ts +235 -235
  49. package/src/markets/morphoBlue/index.ts +895 -895
  50. package/src/markets/spark/index.ts +29 -29
  51. package/src/markets/spark/marketAssets.ts +11 -11
  52. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  53. package/src/morphoBlue/index.ts +222 -222
  54. package/src/portfolio/index.ts +285 -285
  55. package/src/services/priceService.ts +159 -159
  56. package/src/services/utils.ts +63 -63
  57. package/src/services/viem.ts +32 -32
  58. package/src/setup.ts +8 -8
  59. package/src/spark/index.ts +456 -456
  60. package/src/staking/staking.ts +194 -193
  61. package/src/types/aave.ts +194 -194
  62. package/src/types/common.ts +88 -88
  63. package/src/types/compound.ts +136 -136
  64. package/src/types/curveUsd.ts +121 -121
  65. package/src/types/euler.ts +174 -174
  66. package/src/types/fluid.ts +450 -450
  67. package/src/types/index.ts +11 -11
  68. package/src/types/liquity.ts +30 -30
  69. package/src/types/liquityV2.ts +126 -126
  70. package/src/types/llamaLend.ts +157 -157
  71. package/src/types/maker.ts +63 -63
  72. package/src/types/morphoBlue.ts +194 -194
  73. package/src/types/portfolio.ts +60 -60
  74. package/src/types/spark.ts +137 -137
@@ -1,260 +1,260 @@
1
- import Dec from 'decimal.js';
2
- import { assetAmountInWei } from '@defisaver/tokens';
3
- import {
4
- EthAddress, EthereumProvider, NetworkNumber,
5
- } from '../../types/common';
6
- import {
7
- calcLeverageLiqPrice, getAssetsTotal, STABLE_ASSETS,
8
- } from '../../moneymarket';
9
- import { calculateInterestEarned } from '../../staking';
10
- import {
11
- EulerV2AggregatedPositionData,
12
- EulerV2AssetsData,
13
- EulerV2UsedAssets,
14
- } from '../../types';
15
- import { EulerV2ViewContractViem } from '../../contracts';
16
- import { borrowOperations } from '../../constants';
17
- import { getViemProvider } from '../../services/viem';
18
-
19
- export const isLeveragedPos = (usedAssets: EulerV2UsedAssets, dustLimit = 5) => {
20
- let borrowUnstable = 0;
21
- let supplyStable = 0;
22
- let borrowStable = 0;
23
- let supplyUnstable = 0;
24
- let longAsset = '';
25
- let shortAsset = '';
26
- let leverageAssetVault = '';
27
- Object.values(usedAssets).forEach(({
28
- symbol, suppliedUsd, borrowedUsd, collateral, vaultAddress,
29
- }) => {
30
- const isSupplied = (+suppliedUsd) > dustLimit; // ignore dust like <limit leftover supply
31
- const isBorrowed = (+borrowedUsd) > dustLimit; // ignore dust like <limit leftover supply
32
- if (isSupplied && STABLE_ASSETS.includes(symbol) && collateral) supplyStable += 1;
33
- if (isBorrowed && STABLE_ASSETS.includes(symbol)) borrowStable += 1;
34
- if (isBorrowed && !STABLE_ASSETS.includes(symbol)) {
35
- borrowUnstable += 1;
36
- shortAsset = symbol;
37
- leverageAssetVault = vaultAddress;
38
- }
39
- if (isSupplied && !STABLE_ASSETS.includes(symbol) && collateral) {
40
- supplyUnstable += 1;
41
- longAsset = symbol;
42
- leverageAssetVault = vaultAddress;
43
- }
44
- });
45
- const isLong = borrowStable > 0 && borrowUnstable === 0 && supplyUnstable === 1 && supplyStable === 0;
46
- const isShort = supplyStable > 0 && supplyUnstable === 0 && borrowUnstable === 1 && borrowStable === 0;
47
- // lsd -> liquid staking derivative
48
- const isLsdLeveraged = supplyUnstable === 1 && borrowUnstable === 1 && shortAsset === 'ETH' && ['stETH', 'wstETH', 'cbETH', 'rETH'].includes(longAsset);
49
- if (isLong) {
50
- return {
51
- leveragedType: 'long',
52
- leveragedAsset: longAsset,
53
- leveragedVault: leverageAssetVault,
54
- };
55
- }
56
- if (isShort) {
57
- return {
58
- leveragedType: 'short',
59
- leveragedAsset: shortAsset,
60
- leveragedVault: leverageAssetVault,
61
- };
62
- }
63
- if (isLsdLeveraged) {
64
- return {
65
- leveragedType: 'lsd-leverage',
66
- leveragedAsset: longAsset,
67
- leveragedVault: leverageAssetVault,
68
- };
69
- }
70
- return {
71
- leveragedType: '',
72
- leveragedAsset: '',
73
- leveragedVault: '',
74
- };
75
- };
76
-
77
- export const calculateNetApy = (usedAssets: EulerV2UsedAssets, assetsData: EulerV2AssetsData) => {
78
- const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
79
- const acc = { ..._acc };
80
- const assetData = assetsData[usedAsset.vaultAddress.toLowerCase()];
81
-
82
- if (usedAsset.isSupplied) {
83
- const amount = usedAsset.suppliedUsd;
84
- acc.suppliedUsd = new Dec(acc.suppliedUsd).add(amount).toString();
85
- const rate = assetData.supplyRate;
86
- const supplyInterest = calculateInterestEarned(amount, rate as string, 'year', true);
87
- acc.supplyInterest = new Dec(acc.supplyInterest).add(supplyInterest.toString()).toString();
88
- }
89
-
90
- if (usedAsset.isBorrowed) {
91
- const amount = usedAsset.borrowedUsd;
92
- acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
93
- const rate = assetData.borrowRate;
94
- const borrowInterest = calculateInterestEarned(amount, rate as string, 'year', true);
95
- acc.borrowInterest = new Dec(acc.borrowInterest).sub(borrowInterest.toString()).toString();
96
- }
97
-
98
- return acc;
99
- }, {
100
- borrowInterest: '0', supplyInterest: '0', incentiveUsd: '0', borrowedUsd: '0', suppliedUsd: '0',
101
- });
102
-
103
- const {
104
- borrowedUsd, suppliedUsd, borrowInterest, supplyInterest, incentiveUsd,
105
- } = sumValues;
106
-
107
- const totalInterestUsd = new Dec(borrowInterest).add(supplyInterest).add(incentiveUsd).toString();
108
- const balance = new Dec(suppliedUsd).sub(borrowedUsd);
109
- const netApy = new Dec(totalInterestUsd).div(balance).times(100).toString();
110
-
111
- return { netApy, totalInterestUsd, incentiveUsd };
112
- };
113
-
114
- export const getEulerV2AggregatedData = ({
115
- usedAssets, assetsData, network, ...rest
116
- }: { usedAssets: EulerV2UsedAssets, assetsData: EulerV2AssetsData, network: NetworkNumber }) => {
117
- const payload = {} as EulerV2AggregatedPositionData;
118
- payload.suppliedUsd = getAssetsTotal(usedAssets, ({ isSupplied }: { isSupplied: boolean }) => isSupplied, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
119
- payload.suppliedCollateralUsd = getAssetsTotal(usedAssets, ({ isSupplied, collateral }: { isSupplied: boolean, collateral: boolean }) => isSupplied && collateral, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
120
- payload.borrowedUsd = getAssetsTotal(usedAssets, ({ isBorrowed }: { isBorrowed: boolean }) => isBorrowed, ({ borrowedUsd }: { borrowedUsd: string }) => borrowedUsd);
121
- payload.borrowLimitUsd = getAssetsTotal(usedAssets, ({ isSupplied, collateral }: { isSupplied: boolean, collateral: boolean }) => isSupplied && collateral, ({ vaultAddress, suppliedUsd }: { vaultAddress: string, suppliedUsd: string }) => new Dec(suppliedUsd).mul(assetsData[vaultAddress.toLowerCase()].collateralFactor));
122
- payload.liquidationLimitUsd = getAssetsTotal(usedAssets, ({ isSupplied, collateral }: { isSupplied: boolean, collateral: boolean }) => isSupplied && collateral, ({ vaultAddress, suppliedUsd }: { vaultAddress: string, suppliedUsd: string }) => new Dec(suppliedUsd).mul(assetsData[vaultAddress.toLowerCase()].liquidationRatio));
123
- const leftToBorrowUsd = new Dec(payload.borrowLimitUsd).sub(payload.borrowedUsd);
124
- payload.leftToBorrowUsd = leftToBorrowUsd.lte('0') ? '0' : leftToBorrowUsd.toString();
125
- payload.ratio = +payload.suppliedUsd ? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
126
- payload.collRatio = +payload.suppliedUsd ? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
127
- const { netApy, incentiveUsd, totalInterestUsd } = calculateNetApy(usedAssets, assetsData);
128
- payload.netApy = netApy;
129
- payload.incentiveUsd = incentiveUsd;
130
- payload.totalInterestUsd = totalInterestUsd;
131
- payload.minRatio = '100';
132
- payload.liqRatio = new Dec(payload.borrowLimitUsd).div(payload.liquidationLimitUsd).toString();
133
- payload.liqPercent = new Dec(payload.borrowLimitUsd).div(payload.liquidationLimitUsd).mul(100).toString();
134
- const { leveragedType, leveragedAsset, leveragedVault } = isLeveragedPos(usedAssets);
135
- payload.leveragedType = leveragedType;
136
- if (leveragedType !== '') {
137
- payload.leveragedAsset = leveragedAsset;
138
- let assetPrice = assetsData[leveragedVault.toLowerCase()].price;
139
- if (leveragedType === 'lsd-leverage') {
140
- const ethAsset = Object.values(assetsData).find((asset) => ['WETH', 'ETH'].includes(asset.symbol));
141
- if (ethAsset) {
142
- payload.leveragedLsdAssetRatio = new Dec(assetsData[leveragedVault.toLowerCase()].price).div(ethAsset.price).toString();
143
- assetPrice = new Dec(assetPrice).div(ethAsset.price).toString();
144
- }
145
- }
146
- payload.liquidationPrice = calcLeverageLiqPrice(leveragedType, assetPrice, payload.borrowedUsd, payload.liquidationLimitUsd);
147
- }
148
- payload.minCollRatio = new Dec(payload.suppliedCollateralUsd).div(payload.borrowLimitUsd).mul(100).toString();
149
- payload.collLiquidationRatio = new Dec(payload.suppliedCollateralUsd).div(payload.liquidationLimitUsd).mul(100).toString();
150
- return payload;
151
- };
152
-
153
- export const getEulerV2BorrowRate = (interestRate: string) => {
154
- const _interestRate = new Dec(interestRate).div(1e27).toString();
155
- const secondsPerYear = 31556953;
156
- const a = new Dec(1).plus(_interestRate).pow(secondsPerYear - 1).toString();
157
- return new Dec(new Dec(a).minus(1)).mul(100).toString();
158
- };
159
-
160
- export const getUtilizationRate = (totalBorrows: string, totalAssets: string) => new Dec(totalBorrows).div(totalAssets).toString();
161
-
162
- export const getEulerV2SupplyRate = (borrowRate: string, utilizationRate: string, _interestFee: string) => {
163
- const interestFee = new Dec(_interestFee).div(10000);
164
- const fee = new Dec(1).minus(interestFee);
165
- return new Dec(borrowRate).mul(utilizationRate).mul(fee).toString();
166
- };
167
-
168
- const getLiquidityChanges = (action: string, amount: string, isBorrowOperation: boolean) => {
169
- let liquidityAdded;
170
- let liquidityRemoved;
171
- if (isBorrowOperation) {
172
- liquidityAdded = action === 'payback' ? amount : '0';
173
- liquidityRemoved = action === 'borrow' ? amount : '0';
174
- } else {
175
- liquidityAdded = action === 'collateral' ? amount : '0';
176
- liquidityRemoved = action === 'withdraw' ? amount : '0';
177
- }
178
- return { liquidityAdded, liquidityRemoved };
179
- };
180
-
181
- export const getApyAfterValuesEstimationEulerV2 = async (actions: { action: string, amount: string, asset: string, vaultAddress: EthAddress }[], provider: EthereumProvider, network: NetworkNumber) => {
182
- const client = getViemProvider(provider, network, { batch: { multicall: true } });
183
- const eulerV2ViewContract = EulerV2ViewContractViem(client, network);
184
- const apyAfterValuesEstimationParams: {
185
- vault: EthAddress;
186
- isBorrowOperation: boolean;
187
- liquidityAdded: BigInt;
188
- liquidityRemoved: BigInt;
189
- }[] = [];
190
- actions.forEach(({
191
- action, amount, asset, vaultAddress,
192
- }) => {
193
- const amountInWei = assetAmountInWei(amount, asset);
194
- const isBorrowOperation = borrowOperations.includes(action);
195
- const { liquidityAdded, liquidityRemoved } = getLiquidityChanges(action, amountInWei, isBorrowOperation);
196
- apyAfterValuesEstimationParams.push({
197
- vault: vaultAddress,
198
- isBorrowOperation: borrowOperations.includes(action),
199
- liquidityAdded: BigInt(liquidityAdded),
200
- liquidityRemoved: BigInt(liquidityRemoved),
201
- });
202
- });
203
-
204
- const res = await Promise.all([
205
- ...actions.map(({ vaultAddress }) => eulerV2ViewContract.read.getVaultInfoFull([vaultAddress])),
206
- // @ts-ignore
207
- eulerV2ViewContract.read.getApyAfterValuesEstimation([apyAfterValuesEstimationParams]),
208
- ]);
209
- const numOfActions = actions.length;
210
- const data: any = {};
211
- for (let i = 0; i < numOfActions; i += 1) {
212
- // @ts-ignore
213
- const _interestRate = res[numOfActions].estimatedBorrowRates[i];
214
- // @ts-ignore
215
- const vaultInfo = res[i][0];
216
- const decimals = vaultInfo.decimals;
217
- const borrowRate = getEulerV2BorrowRate(_interestRate);
218
-
219
- const amount = new Dec(actions[i].amount).mul(10 ** decimals).toString();
220
- const action = actions[i].action;
221
- const isBorrowOperation = borrowOperations.includes(action);
222
- const { liquidityAdded, liquidityRemoved } = getLiquidityChanges(action, amount, isBorrowOperation);
223
-
224
- const totalBorrows = new Dec(vaultInfo.totalBorrows).add(isBorrowOperation ? liquidityRemoved : '0').sub(isBorrowOperation ? liquidityAdded : '0').toString();
225
- const totalAssets = new Dec(vaultInfo.totalAssets).add(isBorrowOperation ? '0' : liquidityAdded).sub(isBorrowOperation ? '0' : liquidityRemoved).toString();
226
- const utilizationRate = getUtilizationRate(totalBorrows, totalAssets);
227
- data[vaultInfo.vaultAddr.toLowerCase()] = {
228
- borrowRate,
229
- supplyRate: getEulerV2SupplyRate(borrowRate, utilizationRate, vaultInfo.interestFee),
230
- };
231
- }
232
- return data;
233
- };
234
-
235
- const xorLastByte = (address: string, xorValue: string): EthAddress => {
236
- // Extract the last byte (2 hex characters)
237
- const lastByte = address.slice(-2);
238
-
239
- // XOR the last byte with the given xorValue
240
-
241
- // eslint-disable-next-line no-bitwise
242
- const xorResult = [...lastByte].map((char, i) => (parseInt(char, 16) ^ parseInt(xorValue[i], 16)).toString(16),
243
- ).join('');
244
-
245
- // Return the full address with the last byte XORed
246
- return `0x${address.slice(0, -2)}${xorResult.padStart(2, '0')}`;
247
- };
248
-
249
- export const getEulerV2SubAccounts = (address: EthAddress): EthAddress[] => {
250
- // Clean the address by removing "0x"
251
- const cleanAddress = address.toLowerCase().replace(/^0x/, '');
252
-
253
- // XOR the last byte with 0x01, 0x02, and 0x03
254
- const xorWith01 = xorLastByte(cleanAddress, '01');
255
- const xorWith02 = xorLastByte(cleanAddress, '02');
256
- const xorWith03 = xorLastByte(cleanAddress, '03');
257
-
258
- // Return an array with all three modified addresses
259
- return [xorWith01, xorWith02, xorWith03];
1
+ import Dec from 'decimal.js';
2
+ import { assetAmountInWei } from '@defisaver/tokens';
3
+ import {
4
+ EthAddress, EthereumProvider, NetworkNumber,
5
+ } from '../../types/common';
6
+ import {
7
+ calcLeverageLiqPrice, getAssetsTotal, STABLE_ASSETS,
8
+ } from '../../moneymarket';
9
+ import { calculateInterestEarned } from '../../staking';
10
+ import {
11
+ EulerV2AggregatedPositionData,
12
+ EulerV2AssetsData,
13
+ EulerV2UsedAssets,
14
+ } from '../../types';
15
+ import { EulerV2ViewContractViem } from '../../contracts';
16
+ import { borrowOperations } from '../../constants';
17
+ import { getViemProvider } from '../../services/viem';
18
+
19
+ export const isLeveragedPos = (usedAssets: EulerV2UsedAssets, dustLimit = 5) => {
20
+ let borrowUnstable = 0;
21
+ let supplyStable = 0;
22
+ let borrowStable = 0;
23
+ let supplyUnstable = 0;
24
+ let longAsset = '';
25
+ let shortAsset = '';
26
+ let leverageAssetVault = '';
27
+ Object.values(usedAssets).forEach(({
28
+ symbol, suppliedUsd, borrowedUsd, collateral, vaultAddress,
29
+ }) => {
30
+ const isSupplied = (+suppliedUsd) > dustLimit; // ignore dust like <limit leftover supply
31
+ const isBorrowed = (+borrowedUsd) > dustLimit; // ignore dust like <limit leftover supply
32
+ if (isSupplied && STABLE_ASSETS.includes(symbol) && collateral) supplyStable += 1;
33
+ if (isBorrowed && STABLE_ASSETS.includes(symbol)) borrowStable += 1;
34
+ if (isBorrowed && !STABLE_ASSETS.includes(symbol)) {
35
+ borrowUnstable += 1;
36
+ shortAsset = symbol;
37
+ leverageAssetVault = vaultAddress;
38
+ }
39
+ if (isSupplied && !STABLE_ASSETS.includes(symbol) && collateral) {
40
+ supplyUnstable += 1;
41
+ longAsset = symbol;
42
+ leverageAssetVault = vaultAddress;
43
+ }
44
+ });
45
+ const isLong = borrowStable > 0 && borrowUnstable === 0 && supplyUnstable === 1 && supplyStable === 0;
46
+ const isShort = supplyStable > 0 && supplyUnstable === 0 && borrowUnstable === 1 && borrowStable === 0;
47
+ // lsd -> liquid staking derivative
48
+ const isLsdLeveraged = supplyUnstable === 1 && borrowUnstable === 1 && shortAsset === 'ETH' && ['stETH', 'wstETH', 'cbETH', 'rETH'].includes(longAsset);
49
+ if (isLong) {
50
+ return {
51
+ leveragedType: 'long',
52
+ leveragedAsset: longAsset,
53
+ leveragedVault: leverageAssetVault,
54
+ };
55
+ }
56
+ if (isShort) {
57
+ return {
58
+ leveragedType: 'short',
59
+ leveragedAsset: shortAsset,
60
+ leveragedVault: leverageAssetVault,
61
+ };
62
+ }
63
+ if (isLsdLeveraged) {
64
+ return {
65
+ leveragedType: 'lsd-leverage',
66
+ leveragedAsset: longAsset,
67
+ leveragedVault: leverageAssetVault,
68
+ };
69
+ }
70
+ return {
71
+ leveragedType: '',
72
+ leveragedAsset: '',
73
+ leveragedVault: '',
74
+ };
75
+ };
76
+
77
+ export const calculateNetApy = (usedAssets: EulerV2UsedAssets, assetsData: EulerV2AssetsData) => {
78
+ const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
79
+ const acc = { ..._acc };
80
+ const assetData = assetsData[usedAsset.vaultAddress.toLowerCase()];
81
+
82
+ if (usedAsset.isSupplied) {
83
+ const amount = usedAsset.suppliedUsd;
84
+ acc.suppliedUsd = new Dec(acc.suppliedUsd).add(amount).toString();
85
+ const rate = assetData.supplyRate;
86
+ const supplyInterest = calculateInterestEarned(amount, rate as string, 'year', true);
87
+ acc.supplyInterest = new Dec(acc.supplyInterest).add(supplyInterest.toString()).toString();
88
+ }
89
+
90
+ if (usedAsset.isBorrowed) {
91
+ const amount = usedAsset.borrowedUsd;
92
+ acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
93
+ const rate = assetData.borrowRate;
94
+ const borrowInterest = calculateInterestEarned(amount, rate as string, 'year', true);
95
+ acc.borrowInterest = new Dec(acc.borrowInterest).sub(borrowInterest.toString()).toString();
96
+ }
97
+
98
+ return acc;
99
+ }, {
100
+ borrowInterest: '0', supplyInterest: '0', incentiveUsd: '0', borrowedUsd: '0', suppliedUsd: '0',
101
+ });
102
+
103
+ const {
104
+ borrowedUsd, suppliedUsd, borrowInterest, supplyInterest, incentiveUsd,
105
+ } = sumValues;
106
+
107
+ const totalInterestUsd = new Dec(borrowInterest).add(supplyInterest).add(incentiveUsd).toString();
108
+ const balance = new Dec(suppliedUsd).sub(borrowedUsd);
109
+ const netApy = new Dec(totalInterestUsd).div(balance).times(100).toString();
110
+
111
+ return { netApy, totalInterestUsd, incentiveUsd };
112
+ };
113
+
114
+ export const getEulerV2AggregatedData = ({
115
+ usedAssets, assetsData, network, ...rest
116
+ }: { usedAssets: EulerV2UsedAssets, assetsData: EulerV2AssetsData, network: NetworkNumber }) => {
117
+ const payload = {} as EulerV2AggregatedPositionData;
118
+ payload.suppliedUsd = getAssetsTotal(usedAssets, ({ isSupplied }: { isSupplied: boolean }) => isSupplied, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
119
+ payload.suppliedCollateralUsd = getAssetsTotal(usedAssets, ({ isSupplied, collateral }: { isSupplied: boolean, collateral: boolean }) => isSupplied && collateral, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
120
+ payload.borrowedUsd = getAssetsTotal(usedAssets, ({ isBorrowed }: { isBorrowed: boolean }) => isBorrowed, ({ borrowedUsd }: { borrowedUsd: string }) => borrowedUsd);
121
+ payload.borrowLimitUsd = getAssetsTotal(usedAssets, ({ isSupplied, collateral }: { isSupplied: boolean, collateral: boolean }) => isSupplied && collateral, ({ vaultAddress, suppliedUsd }: { vaultAddress: string, suppliedUsd: string }) => new Dec(suppliedUsd).mul(assetsData[vaultAddress.toLowerCase()].collateralFactor));
122
+ payload.liquidationLimitUsd = getAssetsTotal(usedAssets, ({ isSupplied, collateral }: { isSupplied: boolean, collateral: boolean }) => isSupplied && collateral, ({ vaultAddress, suppliedUsd }: { vaultAddress: string, suppliedUsd: string }) => new Dec(suppliedUsd).mul(assetsData[vaultAddress.toLowerCase()].liquidationRatio));
123
+ const leftToBorrowUsd = new Dec(payload.borrowLimitUsd).sub(payload.borrowedUsd);
124
+ payload.leftToBorrowUsd = leftToBorrowUsd.lte('0') ? '0' : leftToBorrowUsd.toString();
125
+ payload.ratio = +payload.suppliedUsd ? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
126
+ payload.collRatio = +payload.suppliedUsd ? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
127
+ const { netApy, incentiveUsd, totalInterestUsd } = calculateNetApy(usedAssets, assetsData);
128
+ payload.netApy = netApy;
129
+ payload.incentiveUsd = incentiveUsd;
130
+ payload.totalInterestUsd = totalInterestUsd;
131
+ payload.minRatio = '100';
132
+ payload.liqRatio = new Dec(payload.borrowLimitUsd).div(payload.liquidationLimitUsd).toString();
133
+ payload.liqPercent = new Dec(payload.borrowLimitUsd).div(payload.liquidationLimitUsd).mul(100).toString();
134
+ const { leveragedType, leveragedAsset, leveragedVault } = isLeveragedPos(usedAssets);
135
+ payload.leveragedType = leveragedType;
136
+ if (leveragedType !== '') {
137
+ payload.leveragedAsset = leveragedAsset;
138
+ let assetPrice = assetsData[leveragedVault.toLowerCase()].price;
139
+ if (leveragedType === 'lsd-leverage') {
140
+ const ethAsset = Object.values(assetsData).find((asset) => ['WETH', 'ETH'].includes(asset.symbol));
141
+ if (ethAsset) {
142
+ payload.leveragedLsdAssetRatio = new Dec(assetsData[leveragedVault.toLowerCase()].price).div(ethAsset.price).toString();
143
+ assetPrice = new Dec(assetPrice).div(ethAsset.price).toString();
144
+ }
145
+ }
146
+ payload.liquidationPrice = calcLeverageLiqPrice(leveragedType, assetPrice, payload.borrowedUsd, payload.liquidationLimitUsd);
147
+ }
148
+ payload.minCollRatio = new Dec(payload.suppliedCollateralUsd).div(payload.borrowLimitUsd).mul(100).toString();
149
+ payload.collLiquidationRatio = new Dec(payload.suppliedCollateralUsd).div(payload.liquidationLimitUsd).mul(100).toString();
150
+ return payload;
151
+ };
152
+
153
+ export const getEulerV2BorrowRate = (interestRate: string) => {
154
+ const _interestRate = new Dec(interestRate).div(1e27).toString();
155
+ const secondsPerYear = 31556953;
156
+ const a = new Dec(1).plus(_interestRate).pow(secondsPerYear - 1).toString();
157
+ return new Dec(new Dec(a).minus(1)).mul(100).toString();
158
+ };
159
+
160
+ export const getUtilizationRate = (totalBorrows: string, totalAssets: string) => new Dec(totalBorrows).div(totalAssets).toString();
161
+
162
+ export const getEulerV2SupplyRate = (borrowRate: string, utilizationRate: string, _interestFee: string) => {
163
+ const interestFee = new Dec(_interestFee).div(10000);
164
+ const fee = new Dec(1).minus(interestFee);
165
+ return new Dec(borrowRate).mul(utilizationRate).mul(fee).toString();
166
+ };
167
+
168
+ const getLiquidityChanges = (action: string, amount: string, isBorrowOperation: boolean) => {
169
+ let liquidityAdded;
170
+ let liquidityRemoved;
171
+ if (isBorrowOperation) {
172
+ liquidityAdded = action === 'payback' ? amount : '0';
173
+ liquidityRemoved = action === 'borrow' ? amount : '0';
174
+ } else {
175
+ liquidityAdded = action === 'collateral' ? amount : '0';
176
+ liquidityRemoved = action === 'withdraw' ? amount : '0';
177
+ }
178
+ return { liquidityAdded, liquidityRemoved };
179
+ };
180
+
181
+ export const getApyAfterValuesEstimationEulerV2 = async (actions: { action: string, amount: string, asset: string, vaultAddress: EthAddress }[], provider: EthereumProvider, network: NetworkNumber) => {
182
+ const client = getViemProvider(provider, network, { batch: { multicall: true } });
183
+ const eulerV2ViewContract = EulerV2ViewContractViem(client, network);
184
+ const apyAfterValuesEstimationParams: {
185
+ vault: EthAddress;
186
+ isBorrowOperation: boolean;
187
+ liquidityAdded: BigInt;
188
+ liquidityRemoved: BigInt;
189
+ }[] = [];
190
+ actions.forEach(({
191
+ action, amount, asset, vaultAddress,
192
+ }) => {
193
+ const amountInWei = assetAmountInWei(amount, asset);
194
+ const isBorrowOperation = borrowOperations.includes(action);
195
+ const { liquidityAdded, liquidityRemoved } = getLiquidityChanges(action, amountInWei, isBorrowOperation);
196
+ apyAfterValuesEstimationParams.push({
197
+ vault: vaultAddress,
198
+ isBorrowOperation: borrowOperations.includes(action),
199
+ liquidityAdded: BigInt(liquidityAdded),
200
+ liquidityRemoved: BigInt(liquidityRemoved),
201
+ });
202
+ });
203
+
204
+ const res = await Promise.all([
205
+ ...actions.map(({ vaultAddress }) => eulerV2ViewContract.read.getVaultInfoFull([vaultAddress])),
206
+ // @ts-ignore
207
+ eulerV2ViewContract.read.getApyAfterValuesEstimation([apyAfterValuesEstimationParams]),
208
+ ]);
209
+ const numOfActions = actions.length;
210
+ const data: any = {};
211
+ for (let i = 0; i < numOfActions; i += 1) {
212
+ // @ts-ignore
213
+ const _interestRate = res[numOfActions].estimatedBorrowRates[i];
214
+ // @ts-ignore
215
+ const vaultInfo = res[i][0];
216
+ const decimals = vaultInfo.decimals;
217
+ const borrowRate = getEulerV2BorrowRate(_interestRate);
218
+
219
+ const amount = new Dec(actions[i].amount).mul(10 ** decimals).toString();
220
+ const action = actions[i].action;
221
+ const isBorrowOperation = borrowOperations.includes(action);
222
+ const { liquidityAdded, liquidityRemoved } = getLiquidityChanges(action, amount, isBorrowOperation);
223
+
224
+ const totalBorrows = new Dec(vaultInfo.totalBorrows).add(isBorrowOperation ? liquidityRemoved : '0').sub(isBorrowOperation ? liquidityAdded : '0').toString();
225
+ const totalAssets = new Dec(vaultInfo.totalAssets).add(isBorrowOperation ? '0' : liquidityAdded).sub(isBorrowOperation ? '0' : liquidityRemoved).toString();
226
+ const utilizationRate = getUtilizationRate(totalBorrows, totalAssets);
227
+ data[vaultInfo.vaultAddr.toLowerCase()] = {
228
+ borrowRate,
229
+ supplyRate: getEulerV2SupplyRate(borrowRate, utilizationRate, vaultInfo.interestFee),
230
+ };
231
+ }
232
+ return data;
233
+ };
234
+
235
+ const xorLastByte = (address: string, xorValue: string): EthAddress => {
236
+ // Extract the last byte (2 hex characters)
237
+ const lastByte = address.slice(-2);
238
+
239
+ // XOR the last byte with the given xorValue
240
+
241
+ // eslint-disable-next-line no-bitwise
242
+ const xorResult = [...lastByte].map((char, i) => (parseInt(char, 16) ^ parseInt(xorValue[i], 16)).toString(16),
243
+ ).join('');
244
+
245
+ // Return the full address with the last byte XORed
246
+ return `0x${address.slice(0, -2)}${xorResult.padStart(2, '0')}`;
247
+ };
248
+
249
+ export const getEulerV2SubAccounts = (address: EthAddress): EthAddress[] => {
250
+ // Clean the address by removing "0x"
251
+ const cleanAddress = address.toLowerCase().replace(/^0x/, '');
252
+
253
+ // XOR the last byte with 0x01, 0x02, and 0x03
254
+ const xorWith01 = xorLastByte(cleanAddress, '01');
255
+ const xorWith02 = xorLastByte(cleanAddress, '02');
256
+ const xorWith03 = xorLastByte(cleanAddress, '03');
257
+
258
+ // Return an array with all three modified addresses
259
+ return [xorWith01, xorWith02, xorWith03];
260
260
  };