@defisaver/positions-sdk 2.0.10 → 2.0.11-dev-linea-1

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 (108) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +64 -64
  4. package/cjs/aaveV3/index.js +1 -1
  5. package/cjs/config/contracts.d.ts +194 -33
  6. package/cjs/config/contracts.js +18 -1
  7. package/cjs/contracts.d.ts +1283 -293
  8. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  9. package/cjs/markets/aave/index.js +1 -1
  10. package/cjs/markets/aave/marketAssets.d.ts +4 -0
  11. package/cjs/markets/aave/marketAssets.js +6 -2
  12. package/cjs/markets/compound/index.js +11 -0
  13. package/cjs/markets/compound/marketsAssets.d.ts +7 -0
  14. package/cjs/markets/compound/marketsAssets.js +7 -0
  15. package/cjs/markets/spark/marketAssets.d.ts +1 -0
  16. package/cjs/markets/spark/marketAssets.js +1 -0
  17. package/cjs/portfolio/index.js +2 -2
  18. package/cjs/services/utils.js +1 -1
  19. package/cjs/services/viem.d.ts +46 -0
  20. package/cjs/services/viem.js +2 -0
  21. package/cjs/staking/staking.js +3 -1
  22. package/cjs/types/common.d.ts +2 -1
  23. package/cjs/types/common.js +1 -0
  24. package/esm/aaveV3/index.js +1 -1
  25. package/esm/config/contracts.d.ts +194 -33
  26. package/esm/config/contracts.js +18 -1
  27. package/esm/contracts.d.ts +1283 -293
  28. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  29. package/esm/markets/aave/index.js +1 -1
  30. package/esm/markets/aave/marketAssets.d.ts +4 -0
  31. package/esm/markets/aave/marketAssets.js +5 -1
  32. package/esm/markets/compound/index.js +11 -0
  33. package/esm/markets/compound/marketsAssets.d.ts +7 -0
  34. package/esm/markets/compound/marketsAssets.js +7 -0
  35. package/esm/markets/spark/marketAssets.d.ts +1 -0
  36. package/esm/markets/spark/marketAssets.js +1 -0
  37. package/esm/portfolio/index.js +2 -2
  38. package/esm/services/utils.js +1 -1
  39. package/esm/services/viem.d.ts +46 -0
  40. package/esm/services/viem.js +3 -1
  41. package/esm/staking/staking.js +3 -1
  42. package/esm/types/common.d.ts +2 -1
  43. package/esm/types/common.js +1 -0
  44. package/package.json +47 -47
  45. package/src/aaveV2/index.ts +236 -236
  46. package/src/aaveV3/index.ts +488 -489
  47. package/src/compoundV2/index.ts +240 -240
  48. package/src/compoundV3/index.ts +270 -270
  49. package/src/config/contracts.ts +1107 -1090
  50. package/src/constants/index.ts +6 -6
  51. package/src/contracts.ts +107 -107
  52. package/src/curveUsd/index.ts +250 -250
  53. package/src/eulerV2/index.ts +314 -314
  54. package/src/exchange/index.ts +25 -25
  55. package/src/fluid/index.ts +1568 -1568
  56. package/src/helpers/aaveHelpers/index.ts +170 -170
  57. package/src/helpers/compoundHelpers/index.ts +261 -261
  58. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  59. package/src/helpers/eulerHelpers/index.ts +259 -259
  60. package/src/helpers/fluidHelpers/index.ts +324 -324
  61. package/src/helpers/index.ts +10 -10
  62. package/src/helpers/liquityV2Helpers/index.ts +80 -80
  63. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  64. package/src/helpers/makerHelpers/index.ts +52 -52
  65. package/src/helpers/morphoBlueHelpers/index.ts +390 -390
  66. package/src/helpers/sparkHelpers/index.ts +155 -155
  67. package/src/index.ts +45 -45
  68. package/src/liquity/index.ts +104 -104
  69. package/src/liquityV2/index.ts +408 -408
  70. package/src/llamaLend/index.ts +296 -296
  71. package/src/maker/index.ts +223 -223
  72. package/src/markets/aave/index.ts +116 -116
  73. package/src/markets/aave/marketAssets.ts +49 -44
  74. package/src/markets/compound/index.ts +227 -216
  75. package/src/markets/compound/marketsAssets.ts +90 -83
  76. package/src/markets/curveUsd/index.ts +69 -69
  77. package/src/markets/euler/index.ts +26 -26
  78. package/src/markets/fluid/index.ts +2456 -2456
  79. package/src/markets/index.ts +25 -25
  80. package/src/markets/liquityV2/index.ts +102 -102
  81. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  82. package/src/markets/llamaLend/index.ts +235 -235
  83. package/src/markets/morphoBlue/index.ts +895 -895
  84. package/src/markets/spark/index.ts +29 -29
  85. package/src/markets/spark/marketAssets.ts +11 -10
  86. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  87. package/src/morphoBlue/index.ts +222 -222
  88. package/src/portfolio/index.ts +285 -285
  89. package/src/services/priceService.ts +159 -159
  90. package/src/services/utils.ts +63 -63
  91. package/src/services/viem.ts +32 -30
  92. package/src/setup.ts +8 -8
  93. package/src/spark/index.ts +456 -456
  94. package/src/staking/staking.ts +193 -192
  95. package/src/types/aave.ts +194 -194
  96. package/src/types/common.ts +88 -87
  97. package/src/types/compound.ts +136 -136
  98. package/src/types/curveUsd.ts +121 -121
  99. package/src/types/euler.ts +174 -174
  100. package/src/types/fluid.ts +450 -450
  101. package/src/types/index.ts +11 -11
  102. package/src/types/liquity.ts +30 -30
  103. package/src/types/liquityV2.ts +126 -126
  104. package/src/types/llamaLend.ts +157 -157
  105. package/src/types/maker.ts +63 -63
  106. package/src/types/morphoBlue.ts +194 -194
  107. package/src/types/portfolio.ts +60 -60
  108. 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
  };