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