@defisaver/positions-sdk 2.1.0 → 2.1.1-dev.0

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 (80) 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/liquityV2/index.d.ts +2 -0
  6. package/cjs/liquityV2/index.js +52 -9
  7. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  8. package/esm/liquityV2/index.d.ts +2 -0
  9. package/esm/liquityV2/index.js +48 -7
  10. package/package.json +47 -47
  11. package/src/aaveV2/index.ts +239 -239
  12. package/src/aaveV3/index.ts +516 -516
  13. package/src/aaveV3/merit.ts +94 -94
  14. package/src/aaveV3/merkl.ts +74 -74
  15. package/src/compoundV2/index.ts +244 -244
  16. package/src/compoundV3/index.ts +274 -274
  17. package/src/config/contracts.ts +1129 -1129
  18. package/src/constants/index.ts +6 -6
  19. package/src/contracts.ts +107 -107
  20. package/src/curveUsd/index.ts +250 -250
  21. package/src/eulerV2/index.ts +324 -324
  22. package/src/exchange/index.ts +25 -25
  23. package/src/fluid/index.ts +1638 -1638
  24. package/src/helpers/aaveHelpers/index.ts +169 -169
  25. package/src/helpers/compoundHelpers/index.ts +283 -283
  26. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  27. package/src/helpers/eulerHelpers/index.ts +222 -222
  28. package/src/helpers/fluidHelpers/index.ts +326 -326
  29. package/src/helpers/index.ts +10 -10
  30. package/src/helpers/liquityV2Helpers/index.ts +82 -82
  31. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  32. package/src/helpers/makerHelpers/index.ts +52 -52
  33. package/src/helpers/morphoBlueHelpers/index.ts +390 -390
  34. package/src/helpers/sparkHelpers/index.ts +155 -155
  35. package/src/index.ts +45 -45
  36. package/src/liquity/index.ts +104 -104
  37. package/src/liquityV2/index.ts +464 -418
  38. package/src/llamaLend/index.ts +305 -305
  39. package/src/maker/index.ts +223 -223
  40. package/src/markets/aave/index.ts +116 -116
  41. package/src/markets/aave/marketAssets.ts +49 -49
  42. package/src/markets/compound/index.ts +227 -227
  43. package/src/markets/compound/marketsAssets.ts +90 -90
  44. package/src/markets/curveUsd/index.ts +69 -69
  45. package/src/markets/euler/index.ts +26 -26
  46. package/src/markets/fluid/index.ts +2456 -2456
  47. package/src/markets/index.ts +25 -25
  48. package/src/markets/liquityV2/index.ts +102 -102
  49. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  50. package/src/markets/llamaLend/index.ts +235 -235
  51. package/src/markets/morphoBlue/index.ts +895 -895
  52. package/src/markets/spark/index.ts +29 -29
  53. package/src/markets/spark/marketAssets.ts +11 -11
  54. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  55. package/src/morphoBlue/index.ts +236 -236
  56. package/src/portfolio/index.ts +285 -285
  57. package/src/services/priceService.ts +159 -159
  58. package/src/services/utils.ts +63 -63
  59. package/src/services/viem.ts +32 -32
  60. package/src/setup.ts +8 -8
  61. package/src/spark/index.ts +444 -444
  62. package/src/staking/eligibility.ts +60 -60
  63. package/src/staking/index.ts +1 -1
  64. package/src/staking/staking.ts +169 -169
  65. package/src/types/aave.ts +189 -189
  66. package/src/types/common.ts +105 -105
  67. package/src/types/compound.ts +136 -136
  68. package/src/types/curveUsd.ts +121 -121
  69. package/src/types/euler.ts +175 -175
  70. package/src/types/fluid.ts +448 -448
  71. package/src/types/index.ts +13 -13
  72. package/src/types/liquity.ts +30 -30
  73. package/src/types/liquityV2.ts +126 -126
  74. package/src/types/llamaLend.ts +159 -159
  75. package/src/types/maker.ts +63 -63
  76. package/src/types/merit.ts +1 -1
  77. package/src/types/merkl.ts +70 -70
  78. package/src/types/morphoBlue.ts +194 -194
  79. package/src/types/portfolio.ts +60 -60
  80. package/src/types/spark.ts +135 -135
@@ -1,41 +1,41 @@
1
- import Dec from 'decimal.js';
2
- import { CrvUSDAggregatedPositionData, CrvUSDMarketData, CrvUSDUsedAssets } from '../../types';
3
- import { MMUsedAssets, NetworkNumber } from '../../types/common';
4
- import { calcLeverageLiqPrice, getAssetsTotal, isLeveragedPos } from '../../moneymarket';
5
- import { mapRange } from '../../services/utils';
6
-
7
- export const getCrvUsdAggregatedData = ({
8
- loanExists, usedAssets, network, selectedMarket, numOfBands, ...rest
9
- }:{
10
- loanExists: boolean, usedAssets: CrvUSDUsedAssets, network: NetworkNumber, selectedMarket: CrvUSDMarketData, numOfBands: number | string
11
- }): CrvUSDAggregatedPositionData => {
12
- const payload = {} as CrvUSDAggregatedPositionData;
13
- payload.supplied = getAssetsTotal(usedAssets, ({ isSupplied }: { isSupplied: boolean }) => isSupplied, ({ supplied }: { supplied: string }) => supplied); // this is wrong if we are in soft-liquidations
14
- payload.borrowed = getAssetsTotal(usedAssets, ({ isBorrowed }: { isBorrowed: boolean }) => isBorrowed, ({ borrowed }: { borrowed: string }) => borrowed);
15
- payload.suppliedUsd = getAssetsTotal(usedAssets, ({ isSupplied }: { isSupplied: boolean }) => isSupplied, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
16
- payload.borrowedUsd = getAssetsTotal(usedAssets, ({ isBorrowed }: { isBorrowed: boolean }) => isBorrowed, ({ borrowedUsd }: { borrowedUsd: string }) => borrowedUsd);
17
-
18
- payload.ratio = loanExists
19
- ? new Dec(payload.suppliedUsd)
20
- .dividedBy(payload.borrowedUsd)
21
- .times(100)
22
- .toString()
23
- : '0';
24
-
25
- // this is all approximation
26
- payload.minAllowedRatio = mapRange(numOfBands, 4, 50, 115, 140); // collateral ratio
27
- payload.collFactor = new Dec(1).div(payload.minAllowedRatio).mul(100).toString(); // collateral factor = 1 / collateral ratio
28
- // only take in consideration collAsset
29
- payload.borrowLimitUsd = usedAssets?.[selectedMarket.collAsset]?.isSupplied
30
- ? new Dec(usedAssets[selectedMarket.collAsset].suppliedUsd).mul(payload.collFactor).toString()
31
- : '0';
32
-
33
- const { leveragedType, leveragedAsset } = isLeveragedPos(usedAssets as unknown as MMUsedAssets);
34
- payload.leveragedType = leveragedType;
35
- if (leveragedType !== '') {
36
- payload.leveragedAsset = leveragedAsset;
37
- payload.liquidationPrice = calcLeverageLiqPrice(leveragedType, usedAssets[selectedMarket.collAsset].price, payload.borrowedUsd, payload.borrowLimitUsd);
38
- }
39
-
40
- return payload;
1
+ import Dec from 'decimal.js';
2
+ import { CrvUSDAggregatedPositionData, CrvUSDMarketData, CrvUSDUsedAssets } from '../../types';
3
+ import { MMUsedAssets, NetworkNumber } from '../../types/common';
4
+ import { calcLeverageLiqPrice, getAssetsTotal, isLeveragedPos } from '../../moneymarket';
5
+ import { mapRange } from '../../services/utils';
6
+
7
+ export const getCrvUsdAggregatedData = ({
8
+ loanExists, usedAssets, network, selectedMarket, numOfBands, ...rest
9
+ }:{
10
+ loanExists: boolean, usedAssets: CrvUSDUsedAssets, network: NetworkNumber, selectedMarket: CrvUSDMarketData, numOfBands: number | string
11
+ }): CrvUSDAggregatedPositionData => {
12
+ const payload = {} as CrvUSDAggregatedPositionData;
13
+ payload.supplied = getAssetsTotal(usedAssets, ({ isSupplied }: { isSupplied: boolean }) => isSupplied, ({ supplied }: { supplied: string }) => supplied); // this is wrong if we are in soft-liquidations
14
+ payload.borrowed = getAssetsTotal(usedAssets, ({ isBorrowed }: { isBorrowed: boolean }) => isBorrowed, ({ borrowed }: { borrowed: string }) => borrowed);
15
+ payload.suppliedUsd = getAssetsTotal(usedAssets, ({ isSupplied }: { isSupplied: boolean }) => isSupplied, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
16
+ payload.borrowedUsd = getAssetsTotal(usedAssets, ({ isBorrowed }: { isBorrowed: boolean }) => isBorrowed, ({ borrowedUsd }: { borrowedUsd: string }) => borrowedUsd);
17
+
18
+ payload.ratio = loanExists
19
+ ? new Dec(payload.suppliedUsd)
20
+ .dividedBy(payload.borrowedUsd)
21
+ .times(100)
22
+ .toString()
23
+ : '0';
24
+
25
+ // this is all approximation
26
+ payload.minAllowedRatio = mapRange(numOfBands, 4, 50, 115, 140); // collateral ratio
27
+ payload.collFactor = new Dec(1).div(payload.minAllowedRatio).mul(100).toString(); // collateral factor = 1 / collateral ratio
28
+ // only take in consideration collAsset
29
+ payload.borrowLimitUsd = usedAssets?.[selectedMarket.collAsset]?.isSupplied
30
+ ? new Dec(usedAssets[selectedMarket.collAsset].suppliedUsd).mul(payload.collFactor).toString()
31
+ : '0';
32
+
33
+ const { leveragedType, leveragedAsset } = isLeveragedPos(usedAssets as unknown as MMUsedAssets);
34
+ payload.leveragedType = leveragedType;
35
+ if (leveragedType !== '') {
36
+ payload.leveragedAsset = leveragedAsset;
37
+ payload.liquidationPrice = calcLeverageLiqPrice(leveragedType, usedAssets[selectedMarket.collAsset].price, payload.borrowedUsd, payload.borrowLimitUsd);
38
+ }
39
+
40
+ return payload;
41
41
  };
@@ -1,223 +1,223 @@
1
- import Dec from 'decimal.js';
2
- import { assetAmountInWei } from '@defisaver/tokens';
3
- import {
4
- EthAddress, EthereumProvider, MMAssetsData, NetworkNumber,
5
- } from '../../types/common';
6
- import {
7
- calcLeverageLiqPrice, getAssetsTotal, STABLE_ASSETS,
8
- } from '../../moneymarket';
9
- import { calculateNetApy } 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 getEulerV2AggregatedData = ({
78
- usedAssets, assetsData, network, ...rest
79
- }: { usedAssets: EulerV2UsedAssets, assetsData: EulerV2AssetsData, network: NetworkNumber }) => {
80
- const payload = {} as EulerV2AggregatedPositionData;
81
- payload.suppliedUsd = getAssetsTotal(usedAssets, ({ isSupplied }: { isSupplied: boolean }) => isSupplied, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
82
- payload.suppliedCollateralUsd = getAssetsTotal(usedAssets, ({ isSupplied, collateral }: { isSupplied: boolean, collateral: boolean }) => isSupplied && collateral, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
83
- payload.borrowedUsd = getAssetsTotal(usedAssets, ({ isBorrowed }: { isBorrowed: boolean }) => isBorrowed, ({ borrowedUsd }: { borrowedUsd: string }) => borrowedUsd);
84
- 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));
85
- 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));
86
- const leftToBorrowUsd = new Dec(payload.borrowLimitUsd).sub(payload.borrowedUsd);
87
- payload.leftToBorrowUsd = leftToBorrowUsd.lte('0') ? '0' : leftToBorrowUsd.toString();
88
- payload.ratio = +payload.suppliedUsd ? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
89
- payload.collRatio = +payload.suppliedUsd ? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
90
- const { netApy, incentiveUsd, totalInterestUsd } = calculateNetApy({ usedAssets, assetsData: assetsData as unknown as MMAssetsData });
91
- payload.netApy = netApy;
92
- payload.incentiveUsd = incentiveUsd;
93
- payload.totalInterestUsd = totalInterestUsd;
94
- payload.minRatio = '100';
95
- payload.liqRatio = new Dec(payload.borrowLimitUsd).div(payload.liquidationLimitUsd).toString();
96
- payload.liqPercent = new Dec(payload.borrowLimitUsd).div(payload.liquidationLimitUsd).mul(100).toString();
97
- const { leveragedType, leveragedAsset, leveragedVault } = isLeveragedPos(usedAssets);
98
- payload.leveragedType = leveragedType;
99
- if (leveragedType !== '') {
100
- payload.leveragedAsset = leveragedAsset;
101
- let assetPrice = assetsData[leveragedVault.toLowerCase()].price;
102
- if (leveragedType === 'lsd-leverage') {
103
- const ethAsset = Object.values(assetsData).find((asset) => ['WETH', 'ETH'].includes(asset.symbol));
104
- if (ethAsset) {
105
- payload.leveragedLsdAssetRatio = new Dec(assetsData[leveragedVault.toLowerCase()].price).div(ethAsset.price).toString();
106
- assetPrice = new Dec(assetPrice).div(ethAsset.price).toString();
107
- }
108
- }
109
- payload.liquidationPrice = calcLeverageLiqPrice(leveragedType, assetPrice, payload.borrowedUsd, payload.liquidationLimitUsd);
110
- }
111
- payload.minCollRatio = new Dec(payload.suppliedCollateralUsd).div(payload.borrowLimitUsd).mul(100).toString();
112
- payload.collLiquidationRatio = new Dec(payload.suppliedCollateralUsd).div(payload.liquidationLimitUsd).mul(100).toString();
113
- return payload;
114
- };
115
-
116
- export const getEulerV2BorrowRate = (interestRate: string) => {
117
- const _interestRate = new Dec(interestRate).div(1e27).toString();
118
- const secondsPerYear = 31556953;
119
- const a = new Dec(1).plus(_interestRate).pow(secondsPerYear - 1).toString();
120
- return new Dec(new Dec(a).minus(1)).mul(100).toString();
121
- };
122
-
123
- export const getUtilizationRate = (totalBorrows: string, totalAssets: string) => new Dec(totalBorrows).div(totalAssets).toString();
124
-
125
- export const getEulerV2SupplyRate = (borrowRate: string, utilizationRate: string, _interestFee: string) => {
126
- const interestFee = new Dec(_interestFee).div(10000);
127
- const fee = new Dec(1).minus(interestFee);
128
- return new Dec(borrowRate).mul(utilizationRate).mul(fee).toString();
129
- };
130
-
131
- const getLiquidityChanges = (action: string, amount: string, isBorrowOperation: boolean) => {
132
- let liquidityAdded;
133
- let liquidityRemoved;
134
- if (isBorrowOperation) {
135
- liquidityAdded = action === 'payback' ? amount : '0';
136
- liquidityRemoved = action === 'borrow' ? amount : '0';
137
- } else {
138
- liquidityAdded = action === 'collateral' ? amount : '0';
139
- liquidityRemoved = action === 'withdraw' ? amount : '0';
140
- }
141
- return { liquidityAdded, liquidityRemoved };
142
- };
143
-
144
- export const getApyAfterValuesEstimationEulerV2 = async (actions: { action: string, amount: string, asset: string, vaultAddress: EthAddress }[], provider: EthereumProvider, network: NetworkNumber) => {
145
- const client = getViemProvider(provider, network, { batch: { multicall: true } });
146
- const eulerV2ViewContract = EulerV2ViewContractViem(client, network);
147
- const apyAfterValuesEstimationParams: {
148
- vault: EthAddress;
149
- isBorrowOperation: boolean;
150
- liquidityAdded: BigInt;
151
- liquidityRemoved: BigInt;
152
- }[] = [];
153
- actions.forEach(({
154
- action, amount, asset, vaultAddress,
155
- }) => {
156
- const amountInWei = assetAmountInWei(amount, asset);
157
- const isBorrowOperation = borrowOperations.includes(action);
158
- const { liquidityAdded, liquidityRemoved } = getLiquidityChanges(action, amountInWei, isBorrowOperation);
159
- apyAfterValuesEstimationParams.push({
160
- vault: vaultAddress,
161
- isBorrowOperation: borrowOperations.includes(action),
162
- liquidityAdded: BigInt(liquidityAdded),
163
- liquidityRemoved: BigInt(liquidityRemoved),
164
- });
165
- });
166
-
167
- const res = await Promise.all([
168
- ...actions.map(({ vaultAddress }) => eulerV2ViewContract.read.getVaultInfoFull([vaultAddress])),
169
- // @ts-ignore
170
- eulerV2ViewContract.read.getApyAfterValuesEstimation([apyAfterValuesEstimationParams]),
171
- ]);
172
- const numOfActions = actions.length;
173
- const data: any = {};
174
- for (let i = 0; i < numOfActions; i += 1) {
175
- // @ts-ignore
176
- const _interestRate = res[numOfActions].estimatedBorrowRates[i];
177
- // @ts-ignore
178
- const vaultInfo = res[i][0];
179
- const decimals = vaultInfo.decimals;
180
- const borrowRate = getEulerV2BorrowRate(_interestRate);
181
-
182
- const amount = new Dec(actions[i].amount).mul(10 ** decimals).toString();
183
- const action = actions[i].action;
184
- const isBorrowOperation = borrowOperations.includes(action);
185
- const { liquidityAdded, liquidityRemoved } = getLiquidityChanges(action, amount, isBorrowOperation);
186
-
187
- const totalBorrows = new Dec(vaultInfo.totalBorrows).add(isBorrowOperation ? liquidityRemoved : '0').sub(isBorrowOperation ? liquidityAdded : '0').toString();
188
- const totalAssets = new Dec(vaultInfo.totalAssets).add(isBorrowOperation ? '0' : liquidityAdded).sub(isBorrowOperation ? '0' : liquidityRemoved).toString();
189
- const utilizationRate = getUtilizationRate(totalBorrows, totalAssets);
190
- data[vaultInfo.vaultAddr.toLowerCase()] = {
191
- borrowRate,
192
- supplyRate: getEulerV2SupplyRate(borrowRate, utilizationRate, vaultInfo.interestFee),
193
- };
194
- }
195
- return data;
196
- };
197
-
198
- const xorLastByte = (address: string, xorValue: string): EthAddress => {
199
- // Extract the last byte (2 hex characters)
200
- const lastByte = address.slice(-2);
201
-
202
- // XOR the last byte with the given xorValue
203
-
204
- // eslint-disable-next-line no-bitwise
205
- const xorResult = [...lastByte].map((char, i) => (parseInt(char, 16) ^ parseInt(xorValue[i], 16)).toString(16),
206
- ).join('');
207
-
208
- // Return the full address with the last byte XORed
209
- return `0x${address.slice(0, -2)}${xorResult.padStart(2, '0')}`;
210
- };
211
-
212
- export const getEulerV2SubAccounts = (address: EthAddress): EthAddress[] => {
213
- // Clean the address by removing "0x"
214
- const cleanAddress = address.toLowerCase().replace(/^0x/, '');
215
-
216
- // XOR the last byte with 0x01, 0x02, and 0x03
217
- const xorWith01 = xorLastByte(cleanAddress, '01');
218
- const xorWith02 = xorLastByte(cleanAddress, '02');
219
- const xorWith03 = xorLastByte(cleanAddress, '03');
220
-
221
- // Return an array with all three modified addresses
222
- return [xorWith01, xorWith02, xorWith03];
1
+ import Dec from 'decimal.js';
2
+ import { assetAmountInWei } from '@defisaver/tokens';
3
+ import {
4
+ EthAddress, EthereumProvider, MMAssetsData, NetworkNumber,
5
+ } from '../../types/common';
6
+ import {
7
+ calcLeverageLiqPrice, getAssetsTotal, STABLE_ASSETS,
8
+ } from '../../moneymarket';
9
+ import { calculateNetApy } 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 getEulerV2AggregatedData = ({
78
+ usedAssets, assetsData, network, ...rest
79
+ }: { usedAssets: EulerV2UsedAssets, assetsData: EulerV2AssetsData, network: NetworkNumber }) => {
80
+ const payload = {} as EulerV2AggregatedPositionData;
81
+ payload.suppliedUsd = getAssetsTotal(usedAssets, ({ isSupplied }: { isSupplied: boolean }) => isSupplied, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
82
+ payload.suppliedCollateralUsd = getAssetsTotal(usedAssets, ({ isSupplied, collateral }: { isSupplied: boolean, collateral: boolean }) => isSupplied && collateral, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
83
+ payload.borrowedUsd = getAssetsTotal(usedAssets, ({ isBorrowed }: { isBorrowed: boolean }) => isBorrowed, ({ borrowedUsd }: { borrowedUsd: string }) => borrowedUsd);
84
+ 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));
85
+ 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));
86
+ const leftToBorrowUsd = new Dec(payload.borrowLimitUsd).sub(payload.borrowedUsd);
87
+ payload.leftToBorrowUsd = leftToBorrowUsd.lte('0') ? '0' : leftToBorrowUsd.toString();
88
+ payload.ratio = +payload.suppliedUsd ? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
89
+ payload.collRatio = +payload.suppliedUsd ? new Dec(payload.suppliedCollateralUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
90
+ const { netApy, incentiveUsd, totalInterestUsd } = calculateNetApy({ usedAssets, assetsData: assetsData as unknown as MMAssetsData });
91
+ payload.netApy = netApy;
92
+ payload.incentiveUsd = incentiveUsd;
93
+ payload.totalInterestUsd = totalInterestUsd;
94
+ payload.minRatio = '100';
95
+ payload.liqRatio = new Dec(payload.borrowLimitUsd).div(payload.liquidationLimitUsd).toString();
96
+ payload.liqPercent = new Dec(payload.borrowLimitUsd).div(payload.liquidationLimitUsd).mul(100).toString();
97
+ const { leveragedType, leveragedAsset, leveragedVault } = isLeveragedPos(usedAssets);
98
+ payload.leveragedType = leveragedType;
99
+ if (leveragedType !== '') {
100
+ payload.leveragedAsset = leveragedAsset;
101
+ let assetPrice = assetsData[leveragedVault.toLowerCase()].price;
102
+ if (leveragedType === 'lsd-leverage') {
103
+ const ethAsset = Object.values(assetsData).find((asset) => ['WETH', 'ETH'].includes(asset.symbol));
104
+ if (ethAsset) {
105
+ payload.leveragedLsdAssetRatio = new Dec(assetsData[leveragedVault.toLowerCase()].price).div(ethAsset.price).toString();
106
+ assetPrice = new Dec(assetPrice).div(ethAsset.price).toString();
107
+ }
108
+ }
109
+ payload.liquidationPrice = calcLeverageLiqPrice(leveragedType, assetPrice, payload.borrowedUsd, payload.liquidationLimitUsd);
110
+ }
111
+ payload.minCollRatio = new Dec(payload.suppliedCollateralUsd).div(payload.borrowLimitUsd).mul(100).toString();
112
+ payload.collLiquidationRatio = new Dec(payload.suppliedCollateralUsd).div(payload.liquidationLimitUsd).mul(100).toString();
113
+ return payload;
114
+ };
115
+
116
+ export const getEulerV2BorrowRate = (interestRate: string) => {
117
+ const _interestRate = new Dec(interestRate).div(1e27).toString();
118
+ const secondsPerYear = 31556953;
119
+ const a = new Dec(1).plus(_interestRate).pow(secondsPerYear - 1).toString();
120
+ return new Dec(new Dec(a).minus(1)).mul(100).toString();
121
+ };
122
+
123
+ export const getUtilizationRate = (totalBorrows: string, totalAssets: string) => new Dec(totalBorrows).div(totalAssets).toString();
124
+
125
+ export const getEulerV2SupplyRate = (borrowRate: string, utilizationRate: string, _interestFee: string) => {
126
+ const interestFee = new Dec(_interestFee).div(10000);
127
+ const fee = new Dec(1).minus(interestFee);
128
+ return new Dec(borrowRate).mul(utilizationRate).mul(fee).toString();
129
+ };
130
+
131
+ const getLiquidityChanges = (action: string, amount: string, isBorrowOperation: boolean) => {
132
+ let liquidityAdded;
133
+ let liquidityRemoved;
134
+ if (isBorrowOperation) {
135
+ liquidityAdded = action === 'payback' ? amount : '0';
136
+ liquidityRemoved = action === 'borrow' ? amount : '0';
137
+ } else {
138
+ liquidityAdded = action === 'collateral' ? amount : '0';
139
+ liquidityRemoved = action === 'withdraw' ? amount : '0';
140
+ }
141
+ return { liquidityAdded, liquidityRemoved };
142
+ };
143
+
144
+ export const getApyAfterValuesEstimationEulerV2 = async (actions: { action: string, amount: string, asset: string, vaultAddress: EthAddress }[], provider: EthereumProvider, network: NetworkNumber) => {
145
+ const client = getViemProvider(provider, network, { batch: { multicall: true } });
146
+ const eulerV2ViewContract = EulerV2ViewContractViem(client, network);
147
+ const apyAfterValuesEstimationParams: {
148
+ vault: EthAddress;
149
+ isBorrowOperation: boolean;
150
+ liquidityAdded: BigInt;
151
+ liquidityRemoved: BigInt;
152
+ }[] = [];
153
+ actions.forEach(({
154
+ action, amount, asset, vaultAddress,
155
+ }) => {
156
+ const amountInWei = assetAmountInWei(amount, asset);
157
+ const isBorrowOperation = borrowOperations.includes(action);
158
+ const { liquidityAdded, liquidityRemoved } = getLiquidityChanges(action, amountInWei, isBorrowOperation);
159
+ apyAfterValuesEstimationParams.push({
160
+ vault: vaultAddress,
161
+ isBorrowOperation: borrowOperations.includes(action),
162
+ liquidityAdded: BigInt(liquidityAdded),
163
+ liquidityRemoved: BigInt(liquidityRemoved),
164
+ });
165
+ });
166
+
167
+ const res = await Promise.all([
168
+ ...actions.map(({ vaultAddress }) => eulerV2ViewContract.read.getVaultInfoFull([vaultAddress])),
169
+ // @ts-ignore
170
+ eulerV2ViewContract.read.getApyAfterValuesEstimation([apyAfterValuesEstimationParams]),
171
+ ]);
172
+ const numOfActions = actions.length;
173
+ const data: any = {};
174
+ for (let i = 0; i < numOfActions; i += 1) {
175
+ // @ts-ignore
176
+ const _interestRate = res[numOfActions].estimatedBorrowRates[i];
177
+ // @ts-ignore
178
+ const vaultInfo = res[i][0];
179
+ const decimals = vaultInfo.decimals;
180
+ const borrowRate = getEulerV2BorrowRate(_interestRate);
181
+
182
+ const amount = new Dec(actions[i].amount).mul(10 ** decimals).toString();
183
+ const action = actions[i].action;
184
+ const isBorrowOperation = borrowOperations.includes(action);
185
+ const { liquidityAdded, liquidityRemoved } = getLiquidityChanges(action, amount, isBorrowOperation);
186
+
187
+ const totalBorrows = new Dec(vaultInfo.totalBorrows).add(isBorrowOperation ? liquidityRemoved : '0').sub(isBorrowOperation ? liquidityAdded : '0').toString();
188
+ const totalAssets = new Dec(vaultInfo.totalAssets).add(isBorrowOperation ? '0' : liquidityAdded).sub(isBorrowOperation ? '0' : liquidityRemoved).toString();
189
+ const utilizationRate = getUtilizationRate(totalBorrows, totalAssets);
190
+ data[vaultInfo.vaultAddr.toLowerCase()] = {
191
+ borrowRate,
192
+ supplyRate: getEulerV2SupplyRate(borrowRate, utilizationRate, vaultInfo.interestFee),
193
+ };
194
+ }
195
+ return data;
196
+ };
197
+
198
+ const xorLastByte = (address: string, xorValue: string): EthAddress => {
199
+ // Extract the last byte (2 hex characters)
200
+ const lastByte = address.slice(-2);
201
+
202
+ // XOR the last byte with the given xorValue
203
+
204
+ // eslint-disable-next-line no-bitwise
205
+ const xorResult = [...lastByte].map((char, i) => (parseInt(char, 16) ^ parseInt(xorValue[i], 16)).toString(16),
206
+ ).join('');
207
+
208
+ // Return the full address with the last byte XORed
209
+ return `0x${address.slice(0, -2)}${xorResult.padStart(2, '0')}`;
210
+ };
211
+
212
+ export const getEulerV2SubAccounts = (address: EthAddress): EthAddress[] => {
213
+ // Clean the address by removing "0x"
214
+ const cleanAddress = address.toLowerCase().replace(/^0x/, '');
215
+
216
+ // XOR the last byte with 0x01, 0x02, and 0x03
217
+ const xorWith01 = xorLastByte(cleanAddress, '01');
218
+ const xorWith02 = xorLastByte(cleanAddress, '02');
219
+ const xorWith03 = xorLastByte(cleanAddress, '03');
220
+
221
+ // Return an array with all three modified addresses
222
+ return [xorWith01, xorWith02, xorWith03];
223
223
  };