@defisaver/positions-sdk 1.0.10 → 1.0.11-fluid-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) 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 +113 -49
  5. package/cjs/config/contracts.js +10 -2
  6. package/cjs/contracts.d.ts +1 -0
  7. package/cjs/contracts.js +2 -1
  8. package/cjs/fluid/index.d.ts +2 -0
  9. package/cjs/fluid/index.js +636 -13
  10. package/cjs/helpers/fluidHelpers/index.d.ts +59 -2
  11. package/cjs/helpers/fluidHelpers/index.js +142 -4
  12. package/cjs/helpers/morphoBlueHelpers/index.js +66 -66
  13. package/cjs/markets/aave/marketAssets.js +3 -1
  14. package/cjs/markets/fluid/index.js +276 -245
  15. package/cjs/services/priceService.d.ts +23 -0
  16. package/cjs/services/priceService.js +44 -5
  17. package/cjs/types/contracts/generated/FluidView.d.ts +220 -3
  18. package/cjs/types/contracts/generated/WeETHPriceFeed.d.ts +135 -0
  19. package/cjs/types/contracts/generated/WeETHPriceFeed.js +5 -0
  20. package/cjs/types/contracts/generated/index.d.ts +1 -0
  21. package/cjs/types/fluid.d.ts +39 -10
  22. package/esm/config/contracts.d.ts +113 -49
  23. package/esm/config/contracts.js +10 -2
  24. package/esm/contracts.d.ts +1 -0
  25. package/esm/contracts.js +1 -0
  26. package/esm/fluid/index.d.ts +2 -0
  27. package/esm/fluid/index.js +639 -16
  28. package/esm/helpers/fluidHelpers/index.d.ts +59 -2
  29. package/esm/helpers/fluidHelpers/index.js +137 -3
  30. package/esm/helpers/morphoBlueHelpers/index.js +66 -66
  31. package/esm/markets/aave/marketAssets.js +3 -1
  32. package/esm/markets/fluid/index.js +276 -245
  33. package/esm/services/priceService.d.ts +23 -0
  34. package/esm/services/priceService.js +40 -5
  35. package/esm/types/contracts/generated/FluidView.d.ts +220 -3
  36. package/esm/types/contracts/generated/WeETHPriceFeed.d.ts +135 -0
  37. package/esm/types/contracts/generated/WeETHPriceFeed.js +4 -0
  38. package/esm/types/contracts/generated/index.d.ts +1 -0
  39. package/esm/types/fluid.d.ts +39 -10
  40. package/package.json +54 -54
  41. package/src/aaveV2/index.ts +227 -227
  42. package/src/aaveV3/index.ts +624 -624
  43. package/src/assets/index.ts +60 -60
  44. package/src/chickenBonds/index.ts +123 -123
  45. package/src/compoundV2/index.ts +220 -220
  46. package/src/compoundV3/index.ts +291 -291
  47. package/src/config/contracts.js +1155 -1147
  48. package/src/constants/index.ts +6 -6
  49. package/src/contracts.ts +135 -134
  50. package/src/curveUsd/index.ts +239 -239
  51. package/src/eulerV2/index.ts +303 -303
  52. package/src/exchange/index.ts +17 -17
  53. package/src/fluid/index.ts +1216 -354
  54. package/src/helpers/aaveHelpers/index.ts +203 -203
  55. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  56. package/src/helpers/compoundHelpers/index.ts +248 -248
  57. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  58. package/src/helpers/eulerHelpers/index.ts +234 -234
  59. package/src/helpers/fluidHelpers/index.ts +295 -57
  60. package/src/helpers/index.ts +11 -11
  61. package/src/helpers/liquityV2Helpers/index.ts +80 -80
  62. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  63. package/src/helpers/makerHelpers/index.ts +94 -94
  64. package/src/helpers/morphoBlueHelpers/index.ts +367 -367
  65. package/src/helpers/sparkHelpers/index.ts +154 -154
  66. package/src/index.ts +52 -52
  67. package/src/liquity/index.ts +116 -116
  68. package/src/liquityV2/index.ts +295 -295
  69. package/src/llamaLend/index.ts +275 -275
  70. package/src/maker/index.ts +117 -117
  71. package/src/markets/aave/index.ts +152 -152
  72. package/src/markets/aave/marketAssets.ts +46 -44
  73. package/src/markets/compound/index.ts +213 -213
  74. package/src/markets/compound/marketsAssets.ts +82 -82
  75. package/src/markets/curveUsd/index.ts +69 -69
  76. package/src/markets/euler/index.ts +26 -26
  77. package/src/markets/fluid/index.ts +2043 -2012
  78. package/src/markets/index.ts +27 -27
  79. package/src/markets/liquityV2/index.ts +54 -54
  80. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  81. package/src/markets/llamaLend/index.ts +235 -235
  82. package/src/markets/morphoBlue/index.ts +895 -895
  83. package/src/markets/spark/index.ts +29 -29
  84. package/src/markets/spark/marketAssets.ts +10 -10
  85. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  86. package/src/morphoAaveV2/index.ts +256 -256
  87. package/src/morphoAaveV3/index.ts +630 -630
  88. package/src/morphoBlue/index.ts +202 -202
  89. package/src/multicall/index.ts +33 -33
  90. package/src/services/priceService.ts +130 -91
  91. package/src/services/utils.ts +59 -59
  92. package/src/setup.ts +8 -8
  93. package/src/spark/index.ts +460 -460
  94. package/src/staking/staking.ts +217 -217
  95. package/src/types/aave.ts +275 -275
  96. package/src/types/chickenBonds.ts +45 -45
  97. package/src/types/common.ts +84 -84
  98. package/src/types/compound.ts +133 -133
  99. package/src/types/contracts/generated/FluidView.ts +263 -2
  100. package/src/types/contracts/generated/WeETHPriceFeed.ts +202 -0
  101. package/src/types/contracts/generated/index.ts +1 -0
  102. package/src/types/curveUsd.ts +119 -119
  103. package/src/types/euler.ts +173 -173
  104. package/src/types/fluid.ts +299 -268
  105. package/src/types/index.ts +11 -11
  106. package/src/types/liquity.ts +30 -30
  107. package/src/types/liquityV2.ts +119 -119
  108. package/src/types/llamaLend.ts +155 -155
  109. package/src/types/maker.ts +50 -50
  110. package/src/types/morphoBlue.ts +194 -194
  111. package/src/types/spark.ts +135 -135
@@ -1,217 +1,217 @@
1
- import Dec from 'decimal.js';
2
- import Web3 from 'web3';
3
- import memoize from 'memoizee';
4
- import {
5
- CbEthContract, LidoContract, PotContract, REthContract, wstETHContract,
6
- } from '../contracts';
7
- import { MMAssetsData, MMUsedAssets, NetworkNumber } from '../types/common';
8
- import { ContractEventLog } from '../types/contracts/generated/types';
9
- import { BLOCKS_IN_A_YEAR, SECONDS_PER_YEAR, AVG_BLOCK_TIME } from '../constants';
10
- import { multicall } from '../multicall';
11
- import { aprToApy } from '../moneymarket';
12
-
13
- 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
- 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
- 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
- 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
- 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
- if (!res.ok) throw new Error(`Failed to fetch APY for ${asset}`);
108
- const data = await res.json();
109
- return String(data.apy);
110
- };
111
-
112
- export const STAKING_ASSETS = ['cbETH', 'wstETH', 'cbETH', 'rETH', 'sDAI', 'weETH', 'sUSDe', 'osETH', 'ezETH', 'ETHx', 'rsETH', 'pufETH', 'wrsETH', 'wsuperOETHb', 'sUSDS'];
113
-
114
- export const getStakingApy = memoize(async (asset: string, web3: Web3, blockNumber: 'latest' | number = 'latest', fromBlock: number | undefined = undefined) => {
115
- try {
116
- if (asset === 'stETH' || asset === 'wstETH') return await getStETHApy(web3, fromBlock, blockNumber);
117
- if (asset === 'cbETH') return await getCbETHApy(web3, blockNumber);
118
- if (asset === 'rETH') return await getREthApy(web3, blockNumber);
119
- if (asset === 'sDAI') return await getDsrApy(web3);
120
- if (asset === 'sUSDe') return await getApyFromDfsApi('sUSDe');
121
- if (asset === 'weETH') return await getApyFromDfsApi('weETH');
122
- if (asset === 'ezETH') return await getApyFromDfsApi('ezETH');
123
- if (asset === 'osETH') return await getApyFromDfsApi('osETH');
124
- if (asset === 'ETHx') return await getApyFromDfsApi('ETHx');
125
- if (asset === 'rsETH' || asset === 'wrsETH') return await getApyFromDfsApi('rsETH');
126
- if (asset === 'pufETH') return await getApyFromDfsApi('pufETH');
127
- if (asset === 'wsuperOETHb') return await getSuperOETHApy();
128
- if (asset === 'sUSDS') return await getSsrApy();
129
- } catch (e) {
130
- console.error(`Failed to fetch APY for ${asset}`);
131
- }
132
- return '0';
133
- }, { promise: true, maxAge: 2 * 60 * 1000 });
134
-
135
- export const calculateInterestEarned = (principal: string, interest: string, type: string, apy = false) => {
136
- let interval = 1;
137
-
138
- if (+interest === 0) return 0;
139
-
140
- if (type === 'month') interval = 1 / 12;
141
- if (type === 'week') interval = 1 / 52.1429;
142
-
143
- if (apy) {
144
- // interest rate already compounded
145
- return (+principal * (1 + (+interest / 100 * interval))) - +principal;
146
- }
147
-
148
- return (+principal * (((1 + (+interest / 100) / BLOCKS_IN_A_YEAR)) ** (BLOCKS_IN_A_YEAR * interval))) - +principal; // eslint-disable-line
149
- };
150
-
151
- export const calculateNetApy = ({ usedAssets, assetsData, isMorpho = false }: { usedAssets: MMUsedAssets, assetsData: MMAssetsData, isMorpho?: boolean }) => {
152
- const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
153
- const acc = { ..._acc };
154
- const assetData = assetsData[usedAsset.symbol];
155
-
156
- if (usedAsset.isSupplied) {
157
- const amount = usedAsset.suppliedUsd;
158
- acc.suppliedUsd = new Dec(acc.suppliedUsd).add(amount).toString();
159
- const rate = isMorpho
160
- ? usedAsset.supplyRate === '0' ? assetData.supplyRateP2P : usedAsset.supplyRate
161
- : assetData.supplyRate;
162
- const supplyInterest = calculateInterestEarned(amount, rate as string, 'year', true);
163
- acc.supplyInterest = new Dec(acc.supplyInterest).add(supplyInterest.toString()).toString();
164
- if (assetData.incentiveSupplyApy) {
165
- // take COMP/AAVE yield into account
166
- const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveSupplyApy, 'year', true);
167
- acc.incentiveUsd = new Dec(acc.incentiveUsd).add(incentiveInterest).toString();
168
- }
169
- }
170
-
171
- if (usedAsset.isBorrowed) {
172
- const amount = usedAsset.borrowedUsd;
173
- acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
174
- const rate = isMorpho
175
- ? usedAsset.borrowRate === '0' ? assetData.borrowRateP2P : usedAsset.borrowRate
176
- : (usedAsset.symbol === 'GHO' && assetsData.nativeAsset)
177
- ? usedAsset.discountedBorrowRate
178
- : (usedAsset?.interestMode === '1' ? usedAsset.stableBorrowRate : assetData.borrowRate);
179
- const borrowInterest = calculateInterestEarned(amount, rate as string, 'year', true);
180
- acc.borrowInterest = new Dec(acc.borrowInterest).sub(borrowInterest.toString()).toString();
181
- if (assetData.incentiveBorrowApy) {
182
- // take COMP/AAVE yield into account
183
- const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveBorrowApy, 'year', true);
184
- acc.incentiveUsd = new Dec(acc.incentiveUsd).sub(incentiveInterest).toString();
185
- }
186
- }
187
-
188
- return acc;
189
- }, {
190
- borrowInterest: '0', supplyInterest: '0', incentiveUsd: '0', borrowedUsd: '0', suppliedUsd: '0',
191
- });
192
-
193
- const {
194
- borrowedUsd, suppliedUsd, borrowInterest, supplyInterest, incentiveUsd,
195
- } = sumValues;
196
-
197
- const totalInterestUsd = new Dec(borrowInterest).add(supplyInterest).add(incentiveUsd).toString();
198
- const balance = new Dec(suppliedUsd).sub(borrowedUsd);
199
- const netApy = new Dec(totalInterestUsd).div(balance).times(100).toString();
200
-
201
- return { netApy, totalInterestUsd, incentiveUsd };
202
- };
203
-
204
- export const getWstETHByStETH = async (stETHAmount: string | number, web3: Web3) => wstETHContract(web3, NetworkNumber.Eth).methods.getWstETHByStETH(stETHAmount).call();
205
-
206
- export const getStETHByWstETH = async (wstETHAmount: string | number, web3: Web3) => wstETHContract(web3, NetworkNumber.Eth).methods.getStETHByWstETH(wstETHAmount).call();
207
-
208
- export const getStETHByWstETHMultiple = async (wstEthAmounts: string[] | number[], web3: Web3) => {
209
- const contract = wstETHContract(web3, NetworkNumber.Eth);
210
- const calls = wstEthAmounts.map((amount) => ({
211
- target: contract.options.address,
212
- abiItem: contract.options.jsonInterface.find((i) => i.name === 'getStETHByWstETH'),
213
- params: [amount],
214
- }));
215
- const stEthAmounts = await multicall(calls, web3);
216
- return stEthAmounts.map((arr) => arr[0]);
217
- };
1
+ import Dec from 'decimal.js';
2
+ import Web3 from 'web3';
3
+ import memoize from 'memoizee';
4
+ import {
5
+ CbEthContract, LidoContract, PotContract, REthContract, wstETHContract,
6
+ } from '../contracts';
7
+ import { MMAssetsData, MMUsedAssets, NetworkNumber } from '../types/common';
8
+ import { ContractEventLog } from '../types/contracts/generated/types';
9
+ import { BLOCKS_IN_A_YEAR, SECONDS_PER_YEAR, AVG_BLOCK_TIME } from '../constants';
10
+ import { multicall } from '../multicall';
11
+ import { aprToApy } from '../moneymarket';
12
+
13
+ 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
+ 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
+ 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
+ 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
+ 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
+ if (!res.ok) throw new Error(`Failed to fetch APY for ${asset}`);
108
+ const data = await res.json();
109
+ return String(data.apy);
110
+ };
111
+
112
+ export const STAKING_ASSETS = ['cbETH', 'wstETH', 'cbETH', 'rETH', 'sDAI', 'weETH', 'sUSDe', 'osETH', 'ezETH', 'ETHx', 'rsETH', 'pufETH', 'wrsETH', 'wsuperOETHb', 'sUSDS'];
113
+
114
+ export const getStakingApy = memoize(async (asset: string, web3: Web3, blockNumber: 'latest' | number = 'latest', fromBlock: number | undefined = undefined) => {
115
+ try {
116
+ if (asset === 'stETH' || asset === 'wstETH') return await getStETHApy(web3, fromBlock, blockNumber);
117
+ if (asset === 'cbETH') return await getCbETHApy(web3, blockNumber);
118
+ if (asset === 'rETH') return await getREthApy(web3, blockNumber);
119
+ if (asset === 'sDAI') return await getDsrApy(web3);
120
+ if (asset === 'sUSDe') return await getApyFromDfsApi('sUSDe');
121
+ if (asset === 'weETH') return await getApyFromDfsApi('weETH');
122
+ if (asset === 'ezETH') return await getApyFromDfsApi('ezETH');
123
+ if (asset === 'osETH') return await getApyFromDfsApi('osETH');
124
+ if (asset === 'ETHx') return await getApyFromDfsApi('ETHx');
125
+ if (asset === 'rsETH' || asset === 'wrsETH') return await getApyFromDfsApi('rsETH');
126
+ if (asset === 'pufETH') return await getApyFromDfsApi('pufETH');
127
+ if (asset === 'wsuperOETHb') return await getSuperOETHApy();
128
+ if (asset === 'sUSDS') return await getSsrApy();
129
+ } catch (e) {
130
+ console.error(`Failed to fetch APY for ${asset}`);
131
+ }
132
+ return '0';
133
+ }, { promise: true, maxAge: 2 * 60 * 1000 });
134
+
135
+ export const calculateInterestEarned = (principal: string, interest: string, type: string, apy = false) => {
136
+ let interval = 1;
137
+
138
+ if (+interest === 0) return 0;
139
+
140
+ if (type === 'month') interval = 1 / 12;
141
+ if (type === 'week') interval = 1 / 52.1429;
142
+
143
+ if (apy) {
144
+ // interest rate already compounded
145
+ return (+principal * (1 + (+interest / 100 * interval))) - +principal;
146
+ }
147
+
148
+ return (+principal * (((1 + (+interest / 100) / BLOCKS_IN_A_YEAR)) ** (BLOCKS_IN_A_YEAR * interval))) - +principal; // eslint-disable-line
149
+ };
150
+
151
+ export const calculateNetApy = ({ usedAssets, assetsData, isMorpho = false }: { usedAssets: MMUsedAssets, assetsData: MMAssetsData, isMorpho?: boolean }) => {
152
+ const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
153
+ const acc = { ..._acc };
154
+ const assetData = assetsData[usedAsset.symbol];
155
+
156
+ if (usedAsset.isSupplied) {
157
+ const amount = usedAsset.suppliedUsd;
158
+ acc.suppliedUsd = new Dec(acc.suppliedUsd).add(amount).toString();
159
+ const rate = isMorpho
160
+ ? usedAsset.supplyRate === '0' ? assetData.supplyRateP2P : usedAsset.supplyRate
161
+ : assetData.supplyRate;
162
+ const supplyInterest = calculateInterestEarned(amount, rate as string, 'year', true);
163
+ acc.supplyInterest = new Dec(acc.supplyInterest).add(supplyInterest.toString()).toString();
164
+ if (assetData.incentiveSupplyApy) {
165
+ // take COMP/AAVE yield into account
166
+ const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveSupplyApy, 'year', true);
167
+ acc.incentiveUsd = new Dec(acc.incentiveUsd).add(incentiveInterest).toString();
168
+ }
169
+ }
170
+
171
+ if (usedAsset.isBorrowed) {
172
+ const amount = usedAsset.borrowedUsd;
173
+ acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
174
+ const rate = isMorpho
175
+ ? usedAsset.borrowRate === '0' ? assetData.borrowRateP2P : usedAsset.borrowRate
176
+ : (usedAsset.symbol === 'GHO' && assetsData.nativeAsset)
177
+ ? usedAsset.discountedBorrowRate
178
+ : (usedAsset?.interestMode === '1' ? usedAsset.stableBorrowRate : assetData.borrowRate);
179
+ const borrowInterest = calculateInterestEarned(amount, rate as string, 'year', true);
180
+ acc.borrowInterest = new Dec(acc.borrowInterest).sub(borrowInterest.toString()).toString();
181
+ if (assetData.incentiveBorrowApy) {
182
+ // take COMP/AAVE yield into account
183
+ const incentiveInterest = calculateInterestEarned(amount, assetData.incentiveBorrowApy, 'year', true);
184
+ acc.incentiveUsd = new Dec(acc.incentiveUsd).sub(incentiveInterest).toString();
185
+ }
186
+ }
187
+
188
+ return acc;
189
+ }, {
190
+ borrowInterest: '0', supplyInterest: '0', incentiveUsd: '0', borrowedUsd: '0', suppliedUsd: '0',
191
+ });
192
+
193
+ const {
194
+ borrowedUsd, suppliedUsd, borrowInterest, supplyInterest, incentiveUsd,
195
+ } = sumValues;
196
+
197
+ const totalInterestUsd = new Dec(borrowInterest).add(supplyInterest).add(incentiveUsd).toString();
198
+ const balance = new Dec(suppliedUsd).sub(borrowedUsd);
199
+ const netApy = new Dec(totalInterestUsd).div(balance).times(100).toString();
200
+
201
+ return { netApy, totalInterestUsd, incentiveUsd };
202
+ };
203
+
204
+ export const getWstETHByStETH = async (stETHAmount: string | number, web3: Web3) => wstETHContract(web3, NetworkNumber.Eth).methods.getWstETHByStETH(stETHAmount).call();
205
+
206
+ export const getStETHByWstETH = async (wstETHAmount: string | number, web3: Web3) => wstETHContract(web3, NetworkNumber.Eth).methods.getStETHByWstETH(wstETHAmount).call();
207
+
208
+ export const getStETHByWstETHMultiple = async (wstEthAmounts: string[] | number[], web3: Web3) => {
209
+ const contract = wstETHContract(web3, NetworkNumber.Eth);
210
+ const calls = wstEthAmounts.map((amount) => ({
211
+ target: contract.options.address,
212
+ abiItem: contract.options.jsonInterface.find((i) => i.name === 'getStETHByWstETH'),
213
+ params: [amount],
214
+ }));
215
+ const stEthAmounts = await multicall(calls, web3);
216
+ return stEthAmounts.map((arr) => arr[0]);
217
+ };