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

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