@defisaver/positions-sdk 0.0.182 → 0.0.183-dev-allocator-2

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 (85) hide show
  1. package/.mocharc.json +4 -4
  2. package/.nvmrc +1 -1
  3. package/README.md +69 -69
  4. package/cjs/aaveV3/index.js +3 -3
  5. package/cjs/config/contracts.d.ts +3 -0
  6. package/cjs/config/contracts.js +3 -0
  7. package/cjs/helpers/aaveHelpers/index.js +0 -1
  8. package/cjs/helpers/morphoBlueHelpers/index.d.ts +5 -0
  9. package/cjs/helpers/morphoBlueHelpers/index.js +142 -1
  10. package/cjs/staking/staking.d.ts +2 -3
  11. package/cjs/staking/staking.js +2 -2
  12. package/cjs/types/morphoBlue.d.ts +31 -0
  13. package/esm/aaveV3/index.js +4 -4
  14. package/esm/config/contracts.d.ts +3 -0
  15. package/esm/config/contracts.js +3 -0
  16. package/esm/helpers/aaveHelpers/index.js +0 -1
  17. package/esm/helpers/morphoBlueHelpers/index.d.ts +5 -0
  18. package/esm/helpers/morphoBlueHelpers/index.js +139 -0
  19. package/esm/staking/staking.d.ts +2 -3
  20. package/esm/staking/staking.js +2 -2
  21. package/esm/types/morphoBlue.d.ts +31 -0
  22. package/package.json +49 -49
  23. package/src/aaveV2/index.ts +227 -227
  24. package/src/aaveV3/index.ts +624 -628
  25. package/src/assets/index.ts +60 -60
  26. package/src/chickenBonds/index.ts +123 -123
  27. package/src/compoundV2/index.ts +220 -220
  28. package/src/compoundV3/index.ts +282 -282
  29. package/src/config/contracts.js +1043 -1040
  30. package/src/constants/index.ts +6 -6
  31. package/src/contracts.ts +130 -130
  32. package/src/curveUsd/index.ts +229 -229
  33. package/src/eulerV2/index.ts +303 -303
  34. package/src/exchange/index.ts +17 -17
  35. package/src/helpers/aaveHelpers/index.ts +198 -199
  36. package/src/helpers/chickenBondsHelpers/index.ts +23 -23
  37. package/src/helpers/compoundHelpers/index.ts +246 -246
  38. package/src/helpers/curveUsdHelpers/index.ts +40 -40
  39. package/src/helpers/eulerHelpers/index.ts +232 -232
  40. package/src/helpers/index.ts +8 -8
  41. package/src/helpers/llamaLendHelpers/index.ts +53 -53
  42. package/src/helpers/makerHelpers/index.ts +94 -94
  43. package/src/helpers/morphoBlueHelpers/index.ts +274 -115
  44. package/src/helpers/sparkHelpers/index.ts +150 -150
  45. package/src/index.ts +48 -48
  46. package/src/liquity/index.ts +116 -116
  47. package/src/llamaLend/index.ts +275 -275
  48. package/src/maker/index.ts +117 -117
  49. package/src/markets/aave/index.ts +152 -152
  50. package/src/markets/aave/marketAssets.ts +46 -46
  51. package/src/markets/compound/index.ts +173 -173
  52. package/src/markets/compound/marketsAssets.ts +64 -64
  53. package/src/markets/curveUsd/index.ts +69 -69
  54. package/src/markets/euler/index.ts +26 -26
  55. package/src/markets/index.ts +23 -23
  56. package/src/markets/llamaLend/contractAddresses.ts +141 -141
  57. package/src/markets/llamaLend/index.ts +235 -235
  58. package/src/markets/morphoBlue/index.ts +809 -809
  59. package/src/markets/spark/index.ts +29 -29
  60. package/src/markets/spark/marketAssets.ts +10 -10
  61. package/src/moneymarket/moneymarketCommonService.ts +80 -80
  62. package/src/morphoAaveV2/index.ts +256 -256
  63. package/src/morphoAaveV3/index.ts +630 -630
  64. package/src/morphoBlue/index.ts +171 -171
  65. package/src/multicall/index.ts +22 -22
  66. package/src/services/dsrService.ts +15 -15
  67. package/src/services/priceService.ts +21 -21
  68. package/src/services/utils.ts +56 -56
  69. package/src/setup.ts +8 -8
  70. package/src/spark/index.ts +461 -461
  71. package/src/staking/staking.ts +220 -222
  72. package/src/types/aave.ts +270 -270
  73. package/src/types/chickenBonds.ts +45 -45
  74. package/src/types/common.ts +84 -84
  75. package/src/types/compound.ts +129 -129
  76. package/src/types/curveUsd.ts +118 -118
  77. package/src/types/euler.ts +171 -171
  78. package/src/types/index.ts +9 -9
  79. package/src/types/liquity.ts +30 -30
  80. package/src/types/llamaLend.ts +155 -155
  81. package/src/types/maker.ts +50 -50
  82. package/src/types/morphoBlue.ts +184 -154
  83. package/src/types/spark.ts +131 -131
  84. package/.vscode/launch.json +0 -17
  85. package/.vscode/settings.json +0 -37
@@ -11,8 +11,10 @@ import Dec from 'decimal.js';
11
11
  import { assetAmountInWei } from '@defisaver/tokens';
12
12
  import { calcLeverageLiqPrice, getAssetsTotal, isLeveragedPos } from '../../moneymarket';
13
13
  import { calculateNetApy } from '../../staking';
14
+ import { NetworkNumber } from '../../types/common';
14
15
  import { borrowOperations, SECONDS_PER_YEAR, WAD } from '../../constants';
15
16
  import { MorphoBlueViewContract } from '../../contracts';
17
+ import { compareAddresses } from '../../services/utils';
16
18
  export const getMorphoBlueAggregatedPositionData = ({ usedAssets, assetsData, marketInfo }) => {
17
19
  var _a, _b, _c, _d, _e, _f;
18
20
  const payload = {};
@@ -100,3 +102,140 @@ export const getApyAfterValuesEstimation = (selectedMarket, action, amount, asse
100
102
  const supplyRate = getSupplyRate(data.market.totalSupplyAssets, data.market.totalBorrowAssets, data.borrowRate, data.market.fee);
101
103
  return { borrowRate, supplyRate };
102
104
  });
105
+ const API_URL = 'https://blue-api.morpho.org/graphql';
106
+ const MARKET_QUERY = `
107
+ query MarketByUniqueKey($uniqueKey: String!, $chainId: Int!) {
108
+ marketByUniqueKey(uniqueKey: $uniqueKey, chainId: $chainId) {
109
+ reallocatableLiquidityAssets
110
+ targetBorrowUtilization
111
+ loanAsset {
112
+ address
113
+ decimals
114
+ priceUsd
115
+ }
116
+ state {
117
+ liquidityAssets
118
+ borrowAssets
119
+ supplyAssets
120
+ }
121
+ publicAllocatorSharedLiquidity {
122
+ assets
123
+ vault {
124
+ address
125
+ name
126
+ }
127
+ allocationMarket {
128
+ uniqueKey
129
+ loanAsset {
130
+ address
131
+ }
132
+ collateralAsset {
133
+ address
134
+ }
135
+ irmAddress
136
+ oracle {
137
+ address
138
+ }
139
+ lltv
140
+ }
141
+ }
142
+ loanAsset {
143
+ address
144
+ }
145
+ collateralAsset {
146
+ address
147
+ }
148
+ oracle {
149
+ address
150
+ }
151
+ irmAddress
152
+ lltv
153
+ }
154
+ }
155
+ `;
156
+ export const getReallocatableLiquidity = (marketId, network = NetworkNumber.Eth) => __awaiter(void 0, void 0, void 0, function* () {
157
+ var _a;
158
+ const response = yield fetch(API_URL, {
159
+ method: 'POST',
160
+ headers: { 'Content-Type': 'application/json' },
161
+ body: JSON.stringify({
162
+ query: MARKET_QUERY,
163
+ variables: { uniqueKey: marketId, chainId: network },
164
+ }),
165
+ });
166
+ const data = yield response.json();
167
+ const marketData = (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.marketByUniqueKey;
168
+ if (!marketData)
169
+ throw new Error('Market data not found');
170
+ return marketData.reallocatableLiquidityAssets;
171
+ });
172
+ export const getReallocation = (marketId, amountToBorrow, network = NetworkNumber.Eth) => __awaiter(void 0, void 0, void 0, function* () {
173
+ var _b, _c, _d;
174
+ const response = yield fetch(API_URL, {
175
+ method: 'POST',
176
+ headers: { 'Content-Type': 'application/json' },
177
+ body: JSON.stringify({
178
+ query: MARKET_QUERY,
179
+ variables: { uniqueKey: marketId, chainId: network },
180
+ }),
181
+ });
182
+ const data = yield response.json();
183
+ const marketData = (_b = data === null || data === void 0 ? void 0 : data.data) === null || _b === void 0 ? void 0 : _b.marketByUniqueKey;
184
+ if (!marketData)
185
+ throw new Error('Market data not found');
186
+ const newTotalBorrowAssets = new Dec(marketData.state.borrowAssets).add(amountToBorrow).toString();
187
+ const leftToBorrow = new Dec(marketData.state.supplyAssets).sub(marketData.state.borrowAssets).toString();
188
+ const newUtil = new Dec(newTotalBorrowAssets).div(marketData.state.supplyAssets).toString();
189
+ const newUtilScaled = new Dec(newUtil).mul(1e18).toString();
190
+ if (new Dec(newUtilScaled).lt(marketData.targetBorrowUtilization))
191
+ return { vaults: [], withdrawals: [] };
192
+ let liquidityToAllocate = new Dec(newTotalBorrowAssets).div(marketData.targetBorrowUtilization).mul(1e18).sub(marketData.state.supplyAssets)
193
+ .toFixed(0)
194
+ .toString();
195
+ if (new Dec(marketData.reallocatableLiquidityAssets).lt(liquidityToAllocate)) {
196
+ liquidityToAllocate = new Dec(amountToBorrow).sub(leftToBorrow).toString();
197
+ if (new Dec(marketData.reallocatableLiquidityAssets).lt(liquidityToAllocate))
198
+ throw new Error('Not enough liquidity available to allocate');
199
+ }
200
+ const vaultTotalAssets = marketData.publicAllocatorSharedLiquidity.reduce((acc, item) => {
201
+ const vaultAddress = item.vault.address;
202
+ acc[vaultAddress] = new Dec(acc[vaultAddress] || '0').add(item.assets).toString();
203
+ return acc;
204
+ }, {});
205
+ const sortedVaults = Object.entries(vaultTotalAssets).sort(([, a], [, b]) => new Dec(b || '0').sub(a || '0').toNumber());
206
+ const withdrawalsPerVault = {};
207
+ let totalReallocated = '0';
208
+ for (const [vaultAddress] of sortedVaults) {
209
+ if (new Dec(totalReallocated).gte(liquidityToAllocate))
210
+ break;
211
+ const vaultAllocations = marketData.publicAllocatorSharedLiquidity.filter((item) => compareAddresses(item.vault.address, vaultAddress));
212
+ for (const item of vaultAllocations) {
213
+ if (new Dec(totalReallocated).gte(liquidityToAllocate))
214
+ break;
215
+ const itemAmount = item.assets;
216
+ const leftToAllocate = new Dec(liquidityToAllocate).sub(totalReallocated).toString();
217
+ const amountToTake = new Dec(itemAmount).lt(leftToAllocate) ? itemAmount : leftToAllocate;
218
+ totalReallocated = new Dec(totalReallocated).add(amountToTake).toString();
219
+ const withdrawal = [
220
+ [
221
+ item.allocationMarket.loanAsset.address,
222
+ (_c = item.allocationMarket.collateralAsset) === null || _c === void 0 ? void 0 : _c.address,
223
+ (_d = item.allocationMarket.oracle) === null || _d === void 0 ? void 0 : _d.address,
224
+ item.allocationMarket.irmAddress,
225
+ item.allocationMarket.lltv,
226
+ ],
227
+ amountToTake.toString(),
228
+ ];
229
+ if (!withdrawalsPerVault[vaultAddress]) {
230
+ withdrawalsPerVault[vaultAddress] = [];
231
+ }
232
+ withdrawalsPerVault[vaultAddress].push(withdrawal);
233
+ }
234
+ }
235
+ const vaults = Object.keys(withdrawalsPerVault);
236
+ const withdrawals = vaults.map((vaultAddress) => withdrawalsPerVault[vaultAddress]);
237
+ return {
238
+ vaults,
239
+ withdrawals,
240
+ };
241
+ });
@@ -1,5 +1,5 @@
1
1
  import Web3 from 'web3';
2
- import { MMAssetsData, MMUsedAssets, NetworkNumber } from '../types/common';
2
+ import { MMAssetsData, MMUsedAssets } from '../types/common';
3
3
  export declare const getStETHApy: (web3: Web3, fromBlock?: number, blockNumber?: 'latest' | number) => Promise<string>;
4
4
  export declare const getCbETHApy: (web3: Web3, blockNumber?: 'latest' | number) => Promise<string>;
5
5
  export declare const getREthApy: (web3: Web3, blockNumber?: 'latest' | number) => Promise<string>;
@@ -8,11 +8,10 @@ export declare const getSsrApy: () => Promise<string>;
8
8
  export declare const STAKING_ASSETS: string[];
9
9
  export declare const getStakingApy: (asset: string, web3: Web3, blockNumber?: 'latest' | number, fromBlock?: number | undefined) => "0" | Promise<any> | undefined;
10
10
  export declare const calculateInterestEarned: (principal: string, interest: string, type: string, apy?: boolean) => number;
11
- export declare const calculateNetApy: ({ usedAssets, assetsData, isMorpho, network, }: {
11
+ export declare const calculateNetApy: ({ usedAssets, assetsData, isMorpho }: {
12
12
  usedAssets: MMUsedAssets;
13
13
  assetsData: MMAssetsData;
14
14
  isMorpho?: boolean | undefined;
15
- network?: NetworkNumber | undefined;
16
15
  }) => {
17
16
  netApy: string;
18
17
  totalInterestUsd: string;
@@ -157,7 +157,7 @@ export const calculateInterestEarned = (principal, interest, type, apy = false)
157
157
  }
158
158
  return (+principal * (Math.pow(((1 + (+interest / 100) / BLOCKS_IN_A_YEAR)), (BLOCKS_IN_A_YEAR * interval)))) - +principal; // eslint-disable-line
159
159
  };
160
- export const calculateNetApy = ({ usedAssets, assetsData, isMorpho = false, network = 1, }) => {
160
+ export const calculateNetApy = ({ usedAssets, assetsData, isMorpho = false }) => {
161
161
  const sumValues = Object.values(usedAssets).reduce((_acc, usedAsset) => {
162
162
  const acc = Object.assign({}, _acc);
163
163
  const assetData = assetsData[usedAsset.symbol];
@@ -180,7 +180,7 @@ export const calculateNetApy = ({ usedAssets, assetsData, isMorpho = false, netw
180
180
  acc.borrowedUsd = new Dec(acc.borrowedUsd).add(amount).toString();
181
181
  const rate = isMorpho
182
182
  ? usedAsset.borrowRate === '0' ? assetData.borrowRateP2P : usedAsset.borrowRate
183
- : (usedAsset.symbol === 'GHO' && network === NetworkNumber.Eth)
183
+ : (usedAsset.symbol === 'GHO' && assetsData.nativeAsset)
184
184
  ? usedAsset.discountedBorrowRate
185
185
  : ((usedAsset === null || usedAsset === void 0 ? void 0 : usedAsset.interestMode) === '1' ? usedAsset.stableBorrowRate : assetData.borrowRate);
186
186
  const borrowInterest = calculateInterestEarned(amount, rate, 'year', true);
@@ -137,3 +137,34 @@ export interface MorphoBluePositionData {
137
137
  supplyShares: string;
138
138
  borrowShares: string;
139
139
  }
140
+ export interface MorphoBlueVault {
141
+ address: string;
142
+ }
143
+ export interface MorphoBlueAllocationMarket {
144
+ loanAsset: {
145
+ address: string;
146
+ };
147
+ collateralAsset: {
148
+ address: string;
149
+ };
150
+ oracle: {
151
+ address: string;
152
+ };
153
+ irmAddress: string;
154
+ lltv: string;
155
+ }
156
+ export interface MorphoBluePublicAllocatorItem {
157
+ vault: MorphoBlueVault;
158
+ assets: string;
159
+ allocationMarket: MorphoBlueAllocationMarket;
160
+ }
161
+ export interface MorphoBlueAllocatorMarketState {
162
+ borrowAssets: string;
163
+ supplyAssets: string;
164
+ }
165
+ export interface MorphoBlueRealloactionMarketData {
166
+ reallocatableLiquidityAssets: string;
167
+ targetBorrowUtilization: string;
168
+ publicAllocatorSharedLiquidity: MorphoBluePublicAllocatorItem[];
169
+ state: MorphoBlueAllocatorMarketState;
170
+ }
package/package.json CHANGED
@@ -1,49 +1,49 @@
1
- {
2
- "name": "@defisaver/positions-sdk",
3
- "version": "0.0.182",
4
- "description": "",
5
- "main": "./cjs/index.js",
6
- "module": "./esm/index.js",
7
- "types": "./esm/index.d.ts",
8
- "scripts": {
9
- "build:esm": "rm -rf esm && tsc -p tsconfig.esm.json",
10
- "build:cjs": "rm -rf cjs && tsc -p tsconfig.cjs.json",
11
- "build": "npm run lint && npm run generate-contracts && npm run build:cjs && npm run build:esm",
12
- "dev": "npm run generate-contracts && tsc -p tsconfig.json --watch",
13
- "lint": "eslint src/ --fix",
14
- "lint-check": "eslint src/",
15
- "generate-contracts": "node scripts/generateContracts.js",
16
- "test": "mocha tests/*",
17
- "test-single": "mocha ./tests/$npm_config_name.ts",
18
- "test:debugger": "mocha --inspect-brk tests/*",
19
- "build-test": "npm run build && npm run test",
20
- "version-bump": "git commit -am \"Version bump to $(npm version patch | cut -c 2-)\""
21
- },
22
- "keywords": [],
23
- "author": "",
24
- "license": "ISC",
25
- "dependencies": {
26
- "@defisaver/tokens": "^1.5.50",
27
- "@ethersproject/bignumber": "^5.7.0",
28
- "@morpho-org/morpho-aave-v3-sdk": "^1.5.3",
29
- "decimal.js": "^10.4.3"
30
- },
31
- "devDependencies": {
32
- "@defisaver/eslint-config": "^1.0.1",
33
- "@types/chai": "^5.0.0",
34
- "@types/mocha": "^10.0.9",
35
- "@types/web3": "^1.0.20",
36
- "chai": "^4.3.8",
37
- "dotenv": "^16.3.1",
38
- "eslint": "^8.49.0",
39
- "eslint-plugin-import": "^2.31.0",
40
- "mocha": "^10.2.0",
41
- "ts-node": "^10.9.2",
42
- "typechain": "^8.3.1",
43
- "typechain-target-web3-v1-3mihai3": "^6.0.2",
44
- "typescript": "^5.2.2"
45
- },
46
- "peerDependencies": {
47
- "web3": "^1.10.2"
48
- }
49
- }
1
+ {
2
+ "name": "@defisaver/positions-sdk",
3
+ "version": "0.0.183-dev-allocator-2",
4
+ "description": "",
5
+ "main": "./cjs/index.js",
6
+ "module": "./esm/index.js",
7
+ "types": "./esm/index.d.ts",
8
+ "scripts": {
9
+ "build:esm": "rm -rf esm && tsc -p tsconfig.esm.json",
10
+ "build:cjs": "rm -rf cjs && tsc -p tsconfig.cjs.json",
11
+ "build": "npm run lint && npm run generate-contracts && npm run build:cjs && npm run build:esm",
12
+ "dev": "npm run generate-contracts && tsc -p tsconfig.json --watch",
13
+ "lint": "eslint src/ --fix",
14
+ "lint-check": "eslint src/",
15
+ "generate-contracts": "node scripts/generateContracts.js",
16
+ "test": "mocha tests/*",
17
+ "test-single": "mocha ./tests/$npm_config_name.ts",
18
+ "test:debugger": "mocha --inspect-brk tests/*",
19
+ "build-test": "npm run build && npm run test",
20
+ "version-bump": "git commit -am \"Version bump to $(npm version patch | cut -c 2-)\""
21
+ },
22
+ "keywords": [],
23
+ "author": "",
24
+ "license": "ISC",
25
+ "dependencies": {
26
+ "@defisaver/tokens": "^1.5.50",
27
+ "@ethersproject/bignumber": "^5.7.0",
28
+ "@morpho-org/morpho-aave-v3-sdk": "^1.5.3",
29
+ "decimal.js": "^10.4.3"
30
+ },
31
+ "devDependencies": {
32
+ "@defisaver/eslint-config": "^1.0.1",
33
+ "@types/chai": "^5.0.0",
34
+ "@types/mocha": "^10.0.9",
35
+ "@types/web3": "^1.0.20",
36
+ "chai": "^4.3.8",
37
+ "dotenv": "^16.3.1",
38
+ "eslint": "^8.49.0",
39
+ "eslint-plugin-import": "^2.31.0",
40
+ "mocha": "^10.2.0",
41
+ "ts-node": "^10.9.2",
42
+ "typechain": "^8.3.1",
43
+ "typechain-target-web3-v1-3mihai3": "^6.0.2",
44
+ "typescript": "^5.2.2"
45
+ },
46
+ "peerDependencies": {
47
+ "web3": "^1.10.2"
48
+ }
49
+ }