@defisaver/positions-sdk 0.0.166-dev → 0.0.166-dev-liquity-v2

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