@defisaver/positions-sdk 0.0.200 → 0.0.201-fluid-dev-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 (135) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +69 -69
  4. package/cjs/config/contracts.d.ts +43 -0
  5. package/cjs/config/contracts.js +6 -0
  6. package/cjs/contracts.d.ts +1 -0
  7. package/cjs/contracts.js +2 -1
  8. package/cjs/fluid/index.d.ts +39 -0
  9. package/cjs/fluid/index.js +216 -0
  10. package/cjs/helpers/fluidHelpers/index.d.ts +6 -0
  11. package/cjs/helpers/fluidHelpers/index.js +40 -0
  12. package/cjs/helpers/index.d.ts +1 -0
  13. package/cjs/helpers/index.js +2 -1
  14. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  15. package/cjs/index.d.ts +2 -1
  16. package/cjs/index.js +3 -1
  17. package/cjs/markets/aave/marketAssets.js +1 -1
  18. package/cjs/markets/fluid/index.d.ts +176 -0
  19. package/cjs/markets/fluid/index.js +1630 -0
  20. package/cjs/markets/index.d.ts +1 -0
  21. package/cjs/markets/index.js +5 -1
  22. package/cjs/morphoBlue/index.js +1 -2
  23. package/cjs/multicall/index.d.ts +1 -0
  24. package/cjs/multicall/index.js +8 -1
  25. package/cjs/services/utils.d.ts +1 -0
  26. package/cjs/services/utils.js +3 -1
  27. package/cjs/types/contracts/generated/FluidView.d.ts +276 -0
  28. package/cjs/types/contracts/generated/FluidView.js +5 -0
  29. package/cjs/types/contracts/generated/index.d.ts +1 -0
  30. package/cjs/types/fluid.d.ts +236 -0
  31. package/cjs/types/fluid.js +129 -0
  32. package/cjs/types/index.d.ts +1 -0
  33. package/cjs/types/index.js +1 -0
  34. package/esm/config/contracts.d.ts +43 -0
  35. package/esm/config/contracts.js +6 -0
  36. package/esm/contracts.d.ts +1 -0
  37. package/esm/contracts.js +1 -0
  38. package/esm/fluid/index.d.ts +39 -0
  39. package/esm/fluid/index.js +205 -0
  40. package/esm/helpers/fluidHelpers/index.d.ts +6 -0
  41. package/esm/helpers/fluidHelpers/index.js +33 -0
  42. package/esm/helpers/index.d.ts +1 -0
  43. package/esm/helpers/index.js +1 -0
  44. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  45. package/esm/index.d.ts +2 -1
  46. package/esm/index.js +2 -1
  47. package/esm/markets/aave/marketAssets.js +1 -1
  48. package/esm/markets/fluid/index.d.ts +176 -0
  49. package/esm/markets/fluid/index.js +1538 -0
  50. package/esm/markets/index.d.ts +1 -0
  51. package/esm/markets/index.js +1 -0
  52. package/esm/morphoBlue/index.js +1 -2
  53. package/esm/multicall/index.d.ts +1 -0
  54. package/esm/multicall/index.js +6 -0
  55. package/esm/services/utils.d.ts +1 -0
  56. package/esm/services/utils.js +1 -0
  57. package/esm/types/contracts/generated/FluidView.d.ts +276 -0
  58. package/esm/types/contracts/generated/FluidView.js +4 -0
  59. package/esm/types/contracts/generated/index.d.ts +1 -0
  60. package/esm/types/fluid.d.ts +236 -0
  61. package/esm/types/fluid.js +126 -0
  62. package/esm/types/index.d.ts +1 -0
  63. package/esm/types/index.js +1 -0
  64. package/package.json +51 -49
  65. package/src/aaveV2/index.ts +227 -227
  66. package/src/aaveV3/index.ts +625 -625
  67. package/src/assets/index.ts +60 -60
  68. package/src/chickenBonds/index.ts +123 -123
  69. package/src/compoundV2/index.ts +220 -220
  70. package/src/compoundV3/index.ts +291 -291
  71. package/src/config/contracts.js +1115 -1109
  72. package/src/constants/index.ts +6 -6
  73. package/src/contracts.ts +134 -133
  74. package/src/curveUsd/index.ts +229 -229
  75. package/src/eulerV2/index.ts +303 -303
  76. package/src/exchange/index.ts +17 -17
  77. package/src/fluid/index.ts +277 -0
  78. package/src/helpers/aaveHelpers/index.ts +198 -198
  79. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  80. package/src/helpers/compoundHelpers/index.ts +246 -246
  81. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  82. package/src/helpers/eulerHelpers/index.ts +232 -232
  83. package/src/helpers/fluidHelpers/index.ts +54 -0
  84. package/src/helpers/index.ts +11 -10
  85. package/src/helpers/liquityV2Helpers/index.ts +79 -79
  86. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  87. package/src/helpers/makerHelpers/index.ts +94 -94
  88. package/src/helpers/morphoBlueHelpers/index.ts +365 -365
  89. package/src/helpers/sparkHelpers/index.ts +150 -150
  90. package/src/index.ts +52 -50
  91. package/src/liquity/index.ts +116 -116
  92. package/src/liquityV2/index.ts +227 -227
  93. package/src/llamaLend/index.ts +275 -275
  94. package/src/maker/index.ts +117 -117
  95. package/src/markets/aave/index.ts +152 -152
  96. package/src/markets/aave/marketAssets.ts +44 -44
  97. package/src/markets/compound/index.ts +213 -213
  98. package/src/markets/compound/marketsAssets.ts +82 -82
  99. package/src/markets/curveUsd/index.ts +69 -69
  100. package/src/markets/euler/index.ts +26 -26
  101. package/src/markets/fluid/index.ts +1635 -0
  102. package/src/markets/index.ts +25 -24
  103. package/src/markets/liquityV2/index.ts +43 -43
  104. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  105. package/src/markets/llamaLend/index.ts +235 -235
  106. package/src/markets/morphoBlue/index.ts +895 -895
  107. package/src/markets/spark/index.ts +29 -29
  108. package/src/markets/spark/marketAssets.ts +10 -10
  109. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  110. package/src/morphoAaveV2/index.ts +256 -256
  111. package/src/morphoAaveV3/index.ts +631 -631
  112. package/src/morphoBlue/index.ts +202 -204
  113. package/src/multicall/index.ts +32 -23
  114. package/src/services/dsrService.ts +15 -15
  115. package/src/services/priceService.ts +62 -62
  116. package/src/services/utils.ts +59 -57
  117. package/src/setup.ts +8 -8
  118. package/src/spark/index.ts +461 -461
  119. package/src/staking/staking.ts +220 -220
  120. package/src/types/aave.ts +271 -271
  121. package/src/types/chickenBonds.ts +45 -45
  122. package/src/types/common.ts +84 -84
  123. package/src/types/compound.ts +131 -131
  124. package/src/types/contracts/generated/FluidView.ts +317 -0
  125. package/src/types/contracts/generated/index.ts +1 -0
  126. package/src/types/curveUsd.ts +118 -118
  127. package/src/types/euler.ts +171 -171
  128. package/src/types/fluid.ts +251 -0
  129. package/src/types/index.ts +12 -11
  130. package/src/types/liquity.ts +30 -30
  131. package/src/types/liquityV2.ts +118 -118
  132. package/src/types/llamaLend.ts +155 -155
  133. package/src/types/maker.ts +50 -50
  134. package/src/types/morphoBlue.ts +192 -192
  135. package/src/types/spark.ts +131 -131
@@ -1,220 +1,220 @@
1
- import Dec from 'decimal.js';
2
- import Web3 from 'web3';
3
- import {
4
- CbEthContract, LidoContract, PotContract, REthContract, wstETHContract,
5
- } from '../contracts';
6
- import { MMAssetsData, MMUsedAssets, NetworkNumber } from '../types/common';
7
- import { ContractEventLog } from '../types/contracts/generated/types';
8
- import { BLOCKS_IN_A_YEAR, SECONDS_PER_YEAR, AVG_BLOCK_TIME } from '../constants';
9
- import { multicall } from '../multicall';
10
- import { aprToApy } from '../moneymarket';
11
-
12
-
13
- export const getStETHApy = async (web3: Web3, fromBlock = 17900000, blockNumber: 'latest' | number = 'latest') => {
14
- try {
15
- const tokenRebasedEvents: ContractEventLog<{ [key: string]: any }>[] = await LidoContract(web3, NetworkNumber.Eth).getPastEvents('TokenRebased', { fromBlock, toBlock: blockNumber });
16
- tokenRebasedEvents.sort((a, b) => b.blockNumber - a.blockNumber); // sort from highest to lowest block number
17
- const movingAverage = 7;
18
- const aprs = tokenRebasedEvents.slice(0, movingAverage).map(({ returnValues: event }) => {
19
- const preShareRate = new Dec(event.preTotalEther.toString()).div(event.preTotalShares.toString());
20
- const postShareRate = new Dec(event.postTotalEther.toString()).div(event.postTotalShares.toString());
21
- return new Dec(SECONDS_PER_YEAR).mul(new Dec(postShareRate).sub(preShareRate).div(preShareRate))
22
- .div(event.timeElapsed.toString()).mul(100)
23
- .toNumber();
24
- });
25
- return aprToApy(aprs.reduce((a, b) => a + b, 0) / aprs.length);
26
- } catch (e) {
27
- console.warn('Failed to fetch stETH APY from events, falling back to Lido API');
28
- const res = await fetch('https://eth-api.lido.fi/v1/protocol/steth/apr/sma');
29
- const data = await res.json();
30
- return aprToApy(data.data.smaApr);
31
- }
32
- };
33
-
34
- export const getCbETHApy = async (web3: Web3, blockNumber: 'latest' | number = 'latest') => {
35
- let currentBlock = blockNumber;
36
- if (blockNumber === 'latest') currentBlock = await web3.eth.getBlockNumber();
37
- const blockDiff = 6 * 24 * 60 * 60 / AVG_BLOCK_TIME;
38
- const pastBlock = (currentBlock as number) - blockDiff;
39
- const contract = CbEthContract(web3, NetworkNumber.Eth);
40
- const [pastRate, currentRate] = await Promise.all([
41
- contract.methods.exchangeRate().call({}, pastBlock),
42
- contract.methods.exchangeRate().call({}, currentBlock),
43
- ]);
44
- const apr = new Dec(currentRate.toString()).sub(pastRate.toString()).div(currentRate.toString())
45
- .mul(BLOCKS_IN_A_YEAR / blockDiff)
46
- .mul(100)
47
- .toString();
48
- return aprToApy(apr);
49
- };
50
-
51
-
52
- export const getREthApy = async (web3: Web3, blockNumber: 'latest' | number = 'latest') => {
53
- let currentBlock = blockNumber;
54
- if (blockNumber === 'latest') currentBlock = await web3.eth.getBlockNumber();
55
- const blockDiff = 8 * 24 * 60 * 60 / AVG_BLOCK_TIME;
56
- const pastBlock = (currentBlock as number) - blockDiff;
57
- const contract = REthContract(web3, NetworkNumber.Eth);
58
- const [pastRate, currentRate] = await Promise.all([
59
- contract.methods.getExchangeRate().call({}, pastBlock),
60
- contract.methods.getExchangeRate().call({}, currentBlock),
61
- ]);
62
- const apr = new Dec(currentRate.toString()).sub(pastRate.toString()).div(currentRate.toString())
63
- .mul(BLOCKS_IN_A_YEAR / blockDiff)
64
- .mul(100)
65
- .toString();
66
-
67
- return aprToApy(apr);
68
- };
69
-
70
- export const getDsrApy = async (web3: Web3, blockNumber: 'latest' | number = 'latest') => {
71
- const potContract = PotContract(web3, NetworkNumber.Eth);
72
- return new Dec(await potContract.methods.dsr().call())
73
- .div(new Dec(1e27))
74
- .pow(SECONDS_PER_YEAR)
75
- .sub(1)
76
- .mul(100)
77
- .toString();
78
- };
79
-
80
- export const getSsrApy = async () => {
81
- const res = await fetch('https://fe.defisaver.com/api/sky/data');
82
- const data = await res.json();
83
- return new Dec(data.data.skyData[0].sky_savings_rate_apy).mul(100).toString();
84
- };
85
-
86
- const getSuperOETHApy = async () => {
87
- const res = await fetch('https://origin.squids.live/origin-squid/graphql', {
88
- method: 'POST',
89
- headers: {
90
- 'Content-Type': 'application/json',
91
- },
92
- body: JSON.stringify({
93
- query: '\n query OTokenApy($chainId: Int!, $token: String!) {\n oTokenApies(\n limit: 1\n orderBy: timestamp_DESC\n where: {chainId_eq: $chainId, otoken_containsInsensitive: $token}\n ) {\n apy7DayAvg\n apy14DayAvg\n apy30DayAvg\n apr\n apy\n }\n}\n ',
94
- variables: {
95
- token: '0xdbfefd2e8460a6ee4955a68582f85708baea60a3',
96
- chainId: 8453,
97
- },
98
- }),
99
- });
100
-
101
- const data = await res.json();
102
- return new Dec(data.data.oTokenApies[0].apy).mul(100).toString();
103
- };
104
-
105
- const getApyFromDfsApi = async (asset: string) => {
106
- const res = await fetch(`https://fe.defisaver.com/api/staking/apy?asset=${asset}`);
107
- const data = await res.json();
108
- // if our server returns apr, transform it into apy
109
- if (['weETH'].includes(asset)) {
110
- return aprToApy(data.apy);
111
- }
112
- return data.apy;
113
- };
114
-
115
- export const STAKING_ASSETS = ['cbETH', 'wstETH', 'cbETH', 'rETH', 'sDAI', 'weETH', 'sUSDe', 'osETH', 'ezETH', 'ETHx', 'rsETH', 'pufETH', 'wrsETH', 'wsuperOETHb', 'sUSDS'];
116
-
117
- export const getStakingApy = (asset: string, web3: Web3, blockNumber: 'latest' | number = 'latest', fromBlock: number | undefined = undefined) => {
118
- try {
119
- if (asset === 'stETH' || asset === 'wstETH') return getStETHApy(web3, fromBlock, blockNumber);
120
- if (asset === 'cbETH') return getCbETHApy(web3, blockNumber);
121
- if (asset === 'rETH') return getREthApy(web3, blockNumber);
122
- if (asset === 'sDAI') return getDsrApy(web3);
123
- if (asset === 'sUSDe') return getApyFromDfsApi('sUSDe');
124
- if (asset === 'weETH') return getApyFromDfsApi('weETH');
125
- if (asset === 'ezETH') return getApyFromDfsApi('ezETH');
126
- if (asset === 'osETH') return getApyFromDfsApi('osETH');
127
- if (asset === 'ETHx') return getApyFromDfsApi('ETHx');
128
- if (asset === 'rsETH' || asset === 'wrsETH') return getApyFromDfsApi('rsETH');
129
- if (asset === 'pufETH') return getApyFromDfsApi('pufETH');
130
- if (asset === 'wsuperOETHb') return getSuperOETHApy();
131
- if (asset === 'sUSDS') return getSsrApy();
132
- } catch (e) {
133
- console.error(`Failed to fetch APY for ${asset}`);
134
- return '0';
135
- }
136
- };
137
-
138
- export const calculateInterestEarned = (principal: string, interest: string, type: string, apy = false) => {
139
- let interval = 1;
140
-
141
- if (+interest === 0) return 0;
142
-
143
- if (type === 'month') interval = 1 / 12;
144
- if (type === 'week') interval = 1 / 52.1429;
145
-
146
- if (apy) {
147
- // interest rate already compounded
148
- return (+principal * (1 + (+interest / 100 * interval))) - +principal;
149
- }
150
-
151
- return (+principal * (((1 + (+interest / 100) / BLOCKS_IN_A_YEAR)) ** (BLOCKS_IN_A_YEAR * interval))) - +principal; // eslint-disable-line
152
- };
153
-
154
- export const calculateNetApy = ({ usedAssets, assetsData, isMorpho = false }: { usedAssets: MMUsedAssets, assetsData: MMAssetsData, isMorpho?: boolean }) => {
155
- const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
156
- const acc = { ..._acc };
157
- const assetData = assetsData[usedAsset.symbol];
158
-
159
- if (usedAsset.isSupplied) {
160
- const amount = usedAsset.suppliedUsd;
161
- acc.suppliedUsd = new Dec(acc.suppliedUsd).add(amount).toString();
162
- const rate = isMorpho
163
- ? usedAsset.supplyRate === '0' ? assetData.supplyRateP2P : usedAsset.supplyRate
164
- : assetData.supplyRate;
165
- const supplyInterest = calculateInterestEarned(amount, rate as string, 'year', true);
166
- acc.supplyInterest = new Dec(acc.supplyInterest).add(supplyInterest.toString()).toString();
167
- if (assetData.incentiveSupplyApy) {
168
- // take COMP/AAVE yield into account
169
- const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveSupplyApy, 'year', true);
170
- acc.incentiveUsd = new Dec(acc.incentiveUsd).add(incentiveInterest).toString();
171
- }
172
- }
173
-
174
- if (usedAsset.isBorrowed) {
175
- const amount = usedAsset.borrowedUsd;
176
- acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
177
- const rate = isMorpho
178
- ? usedAsset.borrowRate === '0' ? assetData.borrowRateP2P : usedAsset.borrowRate
179
- : (usedAsset.symbol === 'GHO' && assetsData.nativeAsset)
180
- ? usedAsset.discountedBorrowRate
181
- : (usedAsset?.interestMode === '1' ? usedAsset.stableBorrowRate : assetData.borrowRate);
182
- const borrowInterest = calculateInterestEarned(amount, rate as string, 'year', true);
183
- acc.borrowInterest = new Dec(acc.borrowInterest).sub(borrowInterest.toString()).toString();
184
- if (assetData.incentiveBorrowApy) {
185
- // take COMP/AAVE yield into account
186
- const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveBorrowApy, 'year', true);
187
- acc.incentiveUsd = new Dec(acc.incentiveUsd).sub(incentiveInterest).toString();
188
- }
189
- }
190
-
191
- return acc;
192
- }, {
193
- borrowInterest: '0', supplyInterest: '0', incentiveUsd: '0', borrowedUsd: '0', suppliedUsd: '0',
194
- });
195
-
196
- const {
197
- borrowedUsd, suppliedUsd, borrowInterest, supplyInterest, incentiveUsd,
198
- } = sumValues;
199
-
200
- const totalInterestUsd = new Dec(borrowInterest).add(supplyInterest).add(incentiveUsd).toString();
201
- const balance = new Dec(suppliedUsd).sub(borrowedUsd);
202
- const netApy = new Dec(totalInterestUsd).div(balance).times(100).toString();
203
-
204
- return { netApy, totalInterestUsd, incentiveUsd };
205
- };
206
-
207
- export const getWstETHByStETH = async (stETHAmount: string | number, web3: Web3) => wstETHContract(web3, NetworkNumber.Eth).methods.getWstETHByStETH(stETHAmount).call();
208
-
209
- export const getStETHByWstETH = async (wstETHAmount: string | number, web3: Web3) => wstETHContract(web3, NetworkNumber.Eth).methods.getStETHByWstETH(wstETHAmount).call();
210
-
211
- export const getStETHByWstETHMultiple = async (wstEthAmounts: string[] | number[], web3: Web3) => {
212
- const contract = wstETHContract(web3, NetworkNumber.Eth);
213
- const calls = wstEthAmounts.map((amount) => ({
214
- target: contract.options.address,
215
- abiItem: contract.options.jsonInterface.find((i) => i.name === 'getStETHByWstETH'),
216
- params: [amount],
217
- }));
218
- const stEthAmounts = await multicall(calls, web3);
219
- return stEthAmounts.map((arr) => arr[0]);
220
- };
1
+ import Dec from 'decimal.js';
2
+ import Web3 from 'web3';
3
+ import {
4
+ CbEthContract, LidoContract, PotContract, REthContract, wstETHContract,
5
+ } from '../contracts';
6
+ import { MMAssetsData, MMUsedAssets, NetworkNumber } from '../types/common';
7
+ import { ContractEventLog } from '../types/contracts/generated/types';
8
+ import { BLOCKS_IN_A_YEAR, SECONDS_PER_YEAR, AVG_BLOCK_TIME } from '../constants';
9
+ import { multicall } from '../multicall';
10
+ import { aprToApy } from '../moneymarket';
11
+
12
+
13
+ export const getStETHApy = async (web3: Web3, fromBlock = 17900000, blockNumber: 'latest' | number = 'latest') => {
14
+ try {
15
+ const tokenRebasedEvents: ContractEventLog<{ [key: string]: any }>[] = await LidoContract(web3, NetworkNumber.Eth).getPastEvents('TokenRebased', { fromBlock, toBlock: blockNumber });
16
+ tokenRebasedEvents.sort((a, b) => b.blockNumber - a.blockNumber); // sort from highest to lowest block number
17
+ const movingAverage = 7;
18
+ const aprs = tokenRebasedEvents.slice(0, movingAverage).map(({ returnValues: event }) => {
19
+ const preShareRate = new Dec(event.preTotalEther.toString()).div(event.preTotalShares.toString());
20
+ const postShareRate = new Dec(event.postTotalEther.toString()).div(event.postTotalShares.toString());
21
+ return new Dec(SECONDS_PER_YEAR).mul(new Dec(postShareRate).sub(preShareRate).div(preShareRate))
22
+ .div(event.timeElapsed.toString()).mul(100)
23
+ .toNumber();
24
+ });
25
+ return aprToApy(aprs.reduce((a, b) => a + b, 0) / aprs.length);
26
+ } catch (e) {
27
+ console.warn('Failed to fetch stETH APY from events, falling back to Lido API');
28
+ const res = await fetch('https://eth-api.lido.fi/v1/protocol/steth/apr/sma');
29
+ const data = await res.json();
30
+ return aprToApy(data.data.smaApr);
31
+ }
32
+ };
33
+
34
+ export const getCbETHApy = async (web3: Web3, blockNumber: 'latest' | number = 'latest') => {
35
+ let currentBlock = blockNumber;
36
+ if (blockNumber === 'latest') currentBlock = await web3.eth.getBlockNumber();
37
+ const blockDiff = 6 * 24 * 60 * 60 / AVG_BLOCK_TIME;
38
+ const pastBlock = (currentBlock as number) - blockDiff;
39
+ const contract = CbEthContract(web3, NetworkNumber.Eth);
40
+ const [pastRate, currentRate] = await Promise.all([
41
+ contract.methods.exchangeRate().call({}, pastBlock),
42
+ contract.methods.exchangeRate().call({}, currentBlock),
43
+ ]);
44
+ const apr = new Dec(currentRate.toString()).sub(pastRate.toString()).div(currentRate.toString())
45
+ .mul(BLOCKS_IN_A_YEAR / blockDiff)
46
+ .mul(100)
47
+ .toString();
48
+ return aprToApy(apr);
49
+ };
50
+
51
+
52
+ export const getREthApy = async (web3: Web3, blockNumber: 'latest' | number = 'latest') => {
53
+ let currentBlock = blockNumber;
54
+ if (blockNumber === 'latest') currentBlock = await web3.eth.getBlockNumber();
55
+ const blockDiff = 8 * 24 * 60 * 60 / AVG_BLOCK_TIME;
56
+ const pastBlock = (currentBlock as number) - blockDiff;
57
+ const contract = REthContract(web3, NetworkNumber.Eth);
58
+ const [pastRate, currentRate] = await Promise.all([
59
+ contract.methods.getExchangeRate().call({}, pastBlock),
60
+ contract.methods.getExchangeRate().call({}, currentBlock),
61
+ ]);
62
+ const apr = new Dec(currentRate.toString()).sub(pastRate.toString()).div(currentRate.toString())
63
+ .mul(BLOCKS_IN_A_YEAR / blockDiff)
64
+ .mul(100)
65
+ .toString();
66
+
67
+ return aprToApy(apr);
68
+ };
69
+
70
+ export const getDsrApy = async (web3: Web3, blockNumber: 'latest' | number = 'latest') => {
71
+ const potContract = PotContract(web3, NetworkNumber.Eth);
72
+ return new Dec(await potContract.methods.dsr().call())
73
+ .div(new Dec(1e27))
74
+ .pow(SECONDS_PER_YEAR)
75
+ .sub(1)
76
+ .mul(100)
77
+ .toString();
78
+ };
79
+
80
+ export const getSsrApy = async () => {
81
+ const res = await fetch('https://fe.defisaver.com/api/sky/data');
82
+ const data = await res.json();
83
+ return new Dec(data.data.skyData[0].sky_savings_rate_apy).mul(100).toString();
84
+ };
85
+
86
+ const getSuperOETHApy = async () => {
87
+ const res = await fetch('https://origin.squids.live/origin-squid/graphql', {
88
+ method: 'POST',
89
+ headers: {
90
+ 'Content-Type': 'application/json',
91
+ },
92
+ body: JSON.stringify({
93
+ query: '\n query OTokenApy($chainId: Int!, $token: String!) {\n oTokenApies(\n limit: 1\n orderBy: timestamp_DESC\n where: {chainId_eq: $chainId, otoken_containsInsensitive: $token}\n ) {\n apy7DayAvg\n apy14DayAvg\n apy30DayAvg\n apr\n apy\n }\n}\n ',
94
+ variables: {
95
+ token: '0xdbfefd2e8460a6ee4955a68582f85708baea60a3',
96
+ chainId: 8453,
97
+ },
98
+ }),
99
+ });
100
+
101
+ const data = await res.json();
102
+ return new Dec(data.data.oTokenApies[0].apy).mul(100).toString();
103
+ };
104
+
105
+ const getApyFromDfsApi = async (asset: string) => {
106
+ const res = await fetch(`https://fe.defisaver.com/api/staking/apy?asset=${asset}`);
107
+ const data = await res.json();
108
+ // if our server returns apr, transform it into apy
109
+ if (['weETH'].includes(asset)) {
110
+ return aprToApy(data.apy);
111
+ }
112
+ return data.apy;
113
+ };
114
+
115
+ export const STAKING_ASSETS = ['cbETH', 'wstETH', 'cbETH', 'rETH', 'sDAI', 'weETH', 'sUSDe', 'osETH', 'ezETH', 'ETHx', 'rsETH', 'pufETH', 'wrsETH', 'wsuperOETHb', 'sUSDS'];
116
+
117
+ export const getStakingApy = (asset: string, web3: Web3, blockNumber: 'latest' | number = 'latest', fromBlock: number | undefined = undefined) => {
118
+ try {
119
+ if (asset === 'stETH' || asset === 'wstETH') return getStETHApy(web3, fromBlock, blockNumber);
120
+ if (asset === 'cbETH') return getCbETHApy(web3, blockNumber);
121
+ if (asset === 'rETH') return getREthApy(web3, blockNumber);
122
+ if (asset === 'sDAI') return getDsrApy(web3);
123
+ if (asset === 'sUSDe') return getApyFromDfsApi('sUSDe');
124
+ if (asset === 'weETH') return getApyFromDfsApi('weETH');
125
+ if (asset === 'ezETH') return getApyFromDfsApi('ezETH');
126
+ if (asset === 'osETH') return getApyFromDfsApi('osETH');
127
+ if (asset === 'ETHx') return getApyFromDfsApi('ETHx');
128
+ if (asset === 'rsETH' || asset === 'wrsETH') return getApyFromDfsApi('rsETH');
129
+ if (asset === 'pufETH') return getApyFromDfsApi('pufETH');
130
+ if (asset === 'wsuperOETHb') return getSuperOETHApy();
131
+ if (asset === 'sUSDS') return getSsrApy();
132
+ } catch (e) {
133
+ console.error(`Failed to fetch APY for ${asset}`);
134
+ return '0';
135
+ }
136
+ };
137
+
138
+ export const calculateInterestEarned = (principal: string, interest: string, type: string, apy = false) => {
139
+ let interval = 1;
140
+
141
+ if (+interest === 0) return 0;
142
+
143
+ if (type === 'month') interval = 1 / 12;
144
+ if (type === 'week') interval = 1 / 52.1429;
145
+
146
+ if (apy) {
147
+ // interest rate already compounded
148
+ return (+principal * (1 + (+interest / 100 * interval))) - +principal;
149
+ }
150
+
151
+ return (+principal * (((1 + (+interest / 100) / BLOCKS_IN_A_YEAR)) ** (BLOCKS_IN_A_YEAR * interval))) - +principal; // eslint-disable-line
152
+ };
153
+
154
+ export const calculateNetApy = ({ usedAssets, assetsData, isMorpho = false }: { usedAssets: MMUsedAssets, assetsData: MMAssetsData, isMorpho?: boolean }) => {
155
+ const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
156
+ const acc = { ..._acc };
157
+ const assetData = assetsData[usedAsset.symbol];
158
+
159
+ if (usedAsset.isSupplied) {
160
+ const amount = usedAsset.suppliedUsd;
161
+ acc.suppliedUsd = new Dec(acc.suppliedUsd).add(amount).toString();
162
+ const rate = isMorpho
163
+ ? usedAsset.supplyRate === '0' ? assetData.supplyRateP2P : usedAsset.supplyRate
164
+ : assetData.supplyRate;
165
+ const supplyInterest = calculateInterestEarned(amount, rate as string, 'year', true);
166
+ acc.supplyInterest = new Dec(acc.supplyInterest).add(supplyInterest.toString()).toString();
167
+ if (assetData.incentiveSupplyApy) {
168
+ // take COMP/AAVE yield into account
169
+ const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveSupplyApy, 'year', true);
170
+ acc.incentiveUsd = new Dec(acc.incentiveUsd).add(incentiveInterest).toString();
171
+ }
172
+ }
173
+
174
+ if (usedAsset.isBorrowed) {
175
+ const amount = usedAsset.borrowedUsd;
176
+ acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
177
+ const rate = isMorpho
178
+ ? usedAsset.borrowRate === '0' ? assetData.borrowRateP2P : usedAsset.borrowRate
179
+ : (usedAsset.symbol === 'GHO' && assetsData.nativeAsset)
180
+ ? usedAsset.discountedBorrowRate
181
+ : (usedAsset?.interestMode === '1' ? usedAsset.stableBorrowRate : assetData.borrowRate);
182
+ const borrowInterest = calculateInterestEarned(amount, rate as string, 'year', true);
183
+ acc.borrowInterest = new Dec(acc.borrowInterest).sub(borrowInterest.toString()).toString();
184
+ if (assetData.incentiveBorrowApy) {
185
+ // take COMP/AAVE yield into account
186
+ const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveBorrowApy, 'year', true);
187
+ acc.incentiveUsd = new Dec(acc.incentiveUsd).sub(incentiveInterest).toString();
188
+ }
189
+ }
190
+
191
+ return acc;
192
+ }, {
193
+ borrowInterest: '0', supplyInterest: '0', incentiveUsd: '0', borrowedUsd: '0', suppliedUsd: '0',
194
+ });
195
+
196
+ const {
197
+ borrowedUsd, suppliedUsd, borrowInterest, supplyInterest, incentiveUsd,
198
+ } = sumValues;
199
+
200
+ const totalInterestUsd = new Dec(borrowInterest).add(supplyInterest).add(incentiveUsd).toString();
201
+ const balance = new Dec(suppliedUsd).sub(borrowedUsd);
202
+ const netApy = new Dec(totalInterestUsd).div(balance).times(100).toString();
203
+
204
+ return { netApy, totalInterestUsd, incentiveUsd };
205
+ };
206
+
207
+ export const getWstETHByStETH = async (stETHAmount: string | number, web3: Web3) => wstETHContract(web3, NetworkNumber.Eth).methods.getWstETHByStETH(stETHAmount).call();
208
+
209
+ export const getStETHByWstETH = async (wstETHAmount: string | number, web3: Web3) => wstETHContract(web3, NetworkNumber.Eth).methods.getStETHByWstETH(wstETHAmount).call();
210
+
211
+ export const getStETHByWstETHMultiple = async (wstEthAmounts: string[] | number[], web3: Web3) => {
212
+ const contract = wstETHContract(web3, NetworkNumber.Eth);
213
+ const calls = wstEthAmounts.map((amount) => ({
214
+ target: contract.options.address,
215
+ abiItem: contract.options.jsonInterface.find((i) => i.name === 'getStETHByWstETH'),
216
+ params: [amount],
217
+ }));
218
+ const stEthAmounts = await multicall(calls, web3);
219
+ return stEthAmounts.map((arr) => arr[0]);
220
+ };