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

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 (142) 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 +232 -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/types/contracts/generated/EulerV2View.d.ts +345 -0
  24. package/cjs/types/contracts/generated/index.d.ts +1 -1
  25. package/cjs/types/euler.d.ts +149 -0
  26. package/cjs/types/euler.js +14 -0
  27. package/cjs/types/index.d.ts +1 -1
  28. package/cjs/types/index.js +1 -1
  29. package/esm/config/contracts.d.ts +32 -3
  30. package/esm/config/contracts.js +3 -3
  31. package/esm/contracts.d.ts +1 -1
  32. package/esm/contracts.js +1 -1
  33. package/esm/eulerV2/index.d.ts +41 -0
  34. package/esm/eulerV2/index.js +210 -0
  35. package/esm/helpers/eulerHelpers/index.d.ts +27 -0
  36. package/esm/helpers/eulerHelpers/index.js +219 -0
  37. package/esm/helpers/index.d.ts +1 -1
  38. package/esm/helpers/index.js +1 -1
  39. package/esm/index.d.ts +2 -2
  40. package/esm/index.js +2 -2
  41. package/esm/markets/euler/index.d.ts +8 -0
  42. package/esm/markets/euler/index.js +24 -0
  43. package/esm/markets/index.d.ts +1 -1
  44. package/esm/markets/index.js +1 -1
  45. package/esm/moneymarket/moneymarketCommonService.js +1 -1
  46. package/esm/services/utils.d.ts +2 -0
  47. package/esm/services/utils.js +2 -0
  48. package/esm/types/contracts/generated/EulerV2View.d.ts +345 -0
  49. package/esm/types/contracts/generated/index.d.ts +1 -1
  50. package/esm/types/euler.d.ts +149 -0
  51. package/esm/types/euler.js +11 -0
  52. package/esm/types/index.d.ts +1 -1
  53. package/esm/types/index.js +1 -1
  54. package/package.json +49 -49
  55. package/src/aaveV2/index.ts +227 -227
  56. package/src/aaveV3/index.ts +590 -590
  57. package/src/assets/index.ts +60 -60
  58. package/src/chickenBonds/index.ts +123 -123
  59. package/src/compoundV2/index.ts +219 -219
  60. package/src/compoundV3/index.ts +281 -281
  61. package/src/config/contracts.js +1040 -1040
  62. package/src/constants/index.ts +6 -6
  63. package/src/contracts.ts +130 -130
  64. package/src/curveUsd/index.ts +229 -229
  65. package/src/eulerV2/index.ts +301 -0
  66. package/src/exchange/index.ts +17 -17
  67. package/src/helpers/aaveHelpers/index.ts +194 -194
  68. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  69. package/src/helpers/compoundHelpers/index.ts +246 -246
  70. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  71. package/src/helpers/eulerHelpers/index.ts +231 -0
  72. package/src/helpers/index.ts +9 -9
  73. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  74. package/src/helpers/makerHelpers/index.ts +94 -94
  75. package/src/helpers/morphoBlueHelpers/index.ts +115 -115
  76. package/src/helpers/sparkHelpers/index.ts +150 -150
  77. package/src/index.ts +48 -48
  78. package/src/liquity/index.ts +116 -116
  79. package/src/llamaLend/index.ts +275 -275
  80. package/src/maker/index.ts +117 -117
  81. package/src/markets/aave/index.ts +152 -152
  82. package/src/markets/aave/marketAssets.ts +46 -46
  83. package/src/markets/compound/index.ts +173 -173
  84. package/src/markets/compound/marketsAssets.ts +64 -64
  85. package/src/markets/curveUsd/index.ts +69 -69
  86. package/src/markets/euler/index.ts +27 -0
  87. package/src/markets/index.ts +24 -23
  88. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  89. package/src/markets/llamaLend/index.ts +235 -235
  90. package/src/markets/morphoBlue/index.ts +728 -728
  91. package/src/markets/spark/index.ts +29 -29
  92. package/src/markets/spark/marketAssets.ts +10 -10
  93. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  94. package/src/morphoAaveV2/index.ts +256 -256
  95. package/src/morphoAaveV3/index.ts +630 -630
  96. package/src/morphoBlue/index.ts +171 -171
  97. package/src/multicall/index.ts +22 -22
  98. package/src/services/dsrService.ts +15 -15
  99. package/src/services/priceService.ts +21 -21
  100. package/src/services/utils.ts +57 -54
  101. package/src/setup.ts +8 -8
  102. package/src/spark/index.ts +424 -424
  103. package/src/staking/staking.ts +218 -218
  104. package/src/types/aave.ts +262 -262
  105. package/src/types/chickenBonds.ts +45 -45
  106. package/src/types/common.ts +84 -84
  107. package/src/types/compound.ts +129 -129
  108. package/src/types/contracts/generated/EulerV2View.ts +446 -0
  109. package/src/types/contracts/generated/index.ts +1 -1
  110. package/src/types/curveUsd.ts +118 -118
  111. package/src/types/euler.ts +172 -0
  112. package/src/types/index.ts +10 -10
  113. package/src/types/liquity.ts +30 -30
  114. package/src/types/llamaLend.ts +155 -155
  115. package/src/types/maker.ts +50 -50
  116. package/src/types/morphoBlue.ts +146 -146
  117. package/src/types/spark.ts +127 -127
  118. package/cjs/helpers/liquityV2Helpers/index.d.ts +0 -12
  119. package/cjs/helpers/liquityV2Helpers/index.js +0 -62
  120. package/cjs/liquityV2/index.d.ts +0 -10
  121. package/cjs/liquityV2/index.js +0 -99
  122. package/cjs/markets/liquityV2/index.d.ts +0 -8
  123. package/cjs/markets/liquityV2/index.js +0 -34
  124. package/cjs/types/contracts/generated/LiquityV2View.d.ts +0 -222
  125. package/cjs/types/liquityV2.d.ts +0 -84
  126. package/cjs/types/liquityV2.js +0 -8
  127. package/esm/helpers/liquityV2Helpers/index.d.ts +0 -12
  128. package/esm/helpers/liquityV2Helpers/index.js +0 -54
  129. package/esm/liquityV2/index.d.ts +0 -10
  130. package/esm/liquityV2/index.js +0 -91
  131. package/esm/markets/liquityV2/index.d.ts +0 -8
  132. package/esm/markets/liquityV2/index.js +0 -28
  133. package/esm/types/contracts/generated/LiquityV2View.d.ts +0 -222
  134. package/esm/types/liquityV2.d.ts +0 -84
  135. package/esm/types/liquityV2.js +0 -5
  136. package/src/helpers/liquityV2Helpers/index.ts +0 -79
  137. package/src/liquityV2/index.ts +0 -116
  138. package/src/markets/liquityV2/index.ts +0 -31
  139. package/src/types/contracts/generated/LiquityV2View.ts +0 -280
  140. package/src/types/liquityV2.ts +0 -90
  141. /package/cjs/types/contracts/generated/{LiquityV2View.js → EulerV2View.js} +0 -0
  142. /package/esm/types/contracts/generated/{LiquityV2View.js → EulerV2View.js} +0 -0
@@ -1,218 +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
- 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
+ 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
+ };