@defisaver/positions-sdk 2.1.158 → 2.1.159

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.
@@ -3,52 +3,100 @@ import Dec from 'decimal.js';
3
3
  import { request as graphqlRequest } from 'graphql-request';
4
4
  import { assetAmountInEth } from '@defisaver/tokens';
5
5
  import * as morphoVaultsOptions from './options';
6
- import { EthAddress, EthereumProvider, NetworkNumber } from '../../types/common';
6
+ import {
7
+ EthAddress, EthereumProvider, NetworkNumber, MorphoVault, MorphoVaultType, SavingsVaultData,
8
+ } from '../../types';
7
9
  import { getViemProvider } from '../../services/viem';
8
10
  import { getMorphoVaultContractViem } from '../../contracts';
9
- import { MorphoVault, SavingsVaultData } from '../../types';
10
11
 
11
12
  export {
12
13
  morphoVaultsOptions,
13
14
  };
14
15
 
15
- const vaultDataQuery = `
16
- query VaultByAddress($address: String!, $chainId: Int!) {
17
- vaultByAddress(address: $address, chainId: $chainId) {
18
- address
19
- state {
20
- totalAssets
21
- totalAssetsUsd
22
- totalSupply
23
- }
24
- liquidity {
25
- underlying
26
- usd
16
+ const MORPHO_BLUE_API = 'https://api.morpho.org/graphql';
17
+
18
+ // Morpho API caps list page size at 100 items
19
+ const MORPHO_API_PAGE_SIZE = 100;
20
+
21
+ const vaultsLiquidityQuery = `
22
+ query VaultsLiquidity($addresses: [String!], $chainIds: [Int!]) {
23
+ vaults(first: ${MORPHO_API_PAGE_SIZE}, where: { address_in: $addresses, chainId_in: $chainIds }) {
24
+ items {
25
+ address
26
+ liquidity {
27
+ underlying
28
+ }
27
29
  }
28
30
  }
29
31
  }`;
30
32
 
31
- const MORPHO_BLUE_API = 'https://api.morpho.org/graphql';
33
+ /**
34
+ * Fetches liquidity for all given vaults in a single API request (chunked if over the page cap),
35
+ * returned as a map keyed by lowercased vault address. A vault missing from the API response is
36
+ * absent from the map.
37
+ */
38
+ export const fetchMorphoVaultsLiquidity = async (network: NetworkNumber, vaults: MorphoVault[]): Promise<Record<string, string>> => {
39
+ const chunks: MorphoVault[][] = [];
40
+ for (let i = 0; i < vaults.length; i += MORPHO_API_PAGE_SIZE) chunks.push(vaults.slice(i, i + MORPHO_API_PAGE_SIZE));
41
+
42
+ const liquidityByAddress: Record<string, string> = {};
43
+ await Promise.all(chunks.map(async (chunk) => {
44
+ const data = await graphqlRequest(MORPHO_BLUE_API, vaultsLiquidityQuery, {
45
+ addresses: chunk.map((vault) => vault.address),
46
+ chainIds: [network],
47
+ // the BigInt scalar serializes as a JSON number when it fits in Number.MAX_SAFE_INTEGER, a string otherwise
48
+ }) as { vaults: { items: { address: string, liquidity: { underlying: string | number | null } | null }[] | null } };
32
49
 
33
- export const _getMorphoVaultData = async (provider: Client, network: NetworkNumber, morphoVault: MorphoVault, accounts: EthAddress[]): Promise<SavingsVaultData> => {
50
+ (data.vaults.items || []).forEach((item) => {
51
+ if (item?.liquidity?.underlying !== undefined && item.liquidity?.underlying !== null) {
52
+ liquidityByAddress[item.address.toLowerCase()] = String(item.liquidity.underlying);
53
+ }
54
+ });
55
+ }));
56
+ return liquidityByAddress;
57
+ };
58
+
59
+ const getBatchedViemProvider = (provider: EthereumProvider, network: NetworkNumber) => getViemProvider(provider, network, {
60
+ batch: {
61
+ multicall: {
62
+ batchSize: 250_000,
63
+ },
64
+ },
65
+ });
66
+
67
+ const getMorphoVaultChainData = async (provider: Client, morphoVault: MorphoVault, accounts: EthAddress[]) => {
34
68
  const morphoVaultContract = getMorphoVaultContractViem(provider, morphoVault.address);
35
69
 
36
70
  const shares: Record<EthAddress, bigint> = {};
37
71
 
38
- const [totalAssets, totalSupply, decimals, decimalsOffset, vaultData] = await Promise.all([
72
+ const [totalAssets, totalSupply, decimals, decimalsOffset] = await Promise.all([
39
73
  morphoVaultContract.read.totalAssets(),
40
74
  morphoVaultContract.read.totalSupply(),
41
75
  morphoVaultContract.read.decimals(),
42
76
  morphoVaultContract.read.DECIMALS_OFFSET(),
43
- graphqlRequest(MORPHO_BLUE_API, vaultDataQuery, { address: morphoVault.address, chainId: network }),
44
77
  ...accounts.map(async (account) => {
45
78
  const share = await morphoVaultContract.read.balanceOf([account]);
46
79
  shares[account] = share;
47
80
  }),
48
81
  ]);
49
82
 
83
+ return {
84
+ totalAssets, totalSupply, decimals, decimalsOffset, shares,
85
+ };
86
+ };
87
+
88
+ const formatMorphoVaultData = (
89
+ morphoVault: MorphoVault,
90
+ chainData: Awaited<ReturnType<typeof getMorphoVaultChainData>>,
91
+ liquidityUnderlying: string,
92
+ accounts: EthAddress[],
93
+ ): SavingsVaultData => {
94
+ const {
95
+ totalAssets, totalSupply, decimals, decimalsOffset, shares,
96
+ } = chainData;
97
+
50
98
  const poolSize = assetAmountInEth(totalAssets.toString(), morphoVault.asset);
51
- const liquidity = assetAmountInEth((vaultData as any).vaultByAddress.liquidity.underlying, morphoVault.asset);
99
+ const liquidity = assetAmountInEth(liquidityUnderlying, morphoVault.asset);
52
100
 
53
101
  const supplied: Record<EthAddress, string> = {};
54
102
  accounts.forEach((account) => {
@@ -67,12 +115,45 @@ export const _getMorphoVaultData = async (provider: Client, network: NetworkNumb
67
115
  };
68
116
  };
69
117
 
118
+ /**
119
+ * Fetches data for all given vaults with a single Morpho API request for their liquidity,
120
+ * instead of one request per vault. The on-chain reads run in parallel with the API request.
121
+ * A vault whose on-chain reads fail or that is missing from the API response is left out of
122
+ * the result; a failed API request rejects, leaving all vaults out.
123
+ */
124
+ export const _getMorphoVaultsData = async (provider: Client, network: NetworkNumber, vaults: MorphoVault[], accounts: EthAddress[]): Promise<Partial<Record<MorphoVaultType, SavingsVaultData>>> => {
125
+ const [liquidityByAddress, chainData] = await Promise.all([
126
+ fetchMorphoVaultsLiquidity(network, vaults),
127
+ Promise.all(vaults.map((vault) => getMorphoVaultChainData(provider, vault, accounts).catch((err) => {
128
+ console.error(`[getMorphoVaultsData] Error fetching on-chain data for morpho vault ${vault.type}:`, err);
129
+ return null;
130
+ }))),
131
+ ]);
132
+
133
+ const savingsData: Partial<Record<MorphoVaultType, SavingsVaultData>> = {};
134
+ vaults.forEach((vault, i) => {
135
+ const vaultChainData = chainData[i];
136
+ if (!vaultChainData) return;
137
+ const liquidityUnderlying = liquidityByAddress[vault.address.toLowerCase()];
138
+ if (liquidityUnderlying === undefined) {
139
+ console.error(`[getMorphoVaultsData] Vault ${vault.type} (${vault.address}) missing from Morpho API response`);
140
+ return;
141
+ }
142
+ savingsData[vault.type] = formatMorphoVaultData(vault, vaultChainData, liquidityUnderlying, accounts);
143
+ });
144
+ return savingsData;
145
+ };
146
+
147
+ export async function getMorphoVaultsData(provider: EthereumProvider, network: NetworkNumber, vaults: MorphoVault[], accounts: EthAddress[]): Promise<Partial<Record<MorphoVaultType, SavingsVaultData>>> {
148
+ return _getMorphoVaultsData(getBatchedViemProvider(provider, network), network, vaults, accounts);
149
+ }
150
+
70
151
  export async function getMorphoVaultData(provider: EthereumProvider, network: NetworkNumber, morphoVault: MorphoVault, accounts: EthAddress[]): Promise<SavingsVaultData> {
71
- return _getMorphoVaultData(getViemProvider(provider, network, {
72
- batch: {
73
- multicall: {
74
- batchSize: 2500000,
75
- },
76
- },
77
- }), network, morphoVault, accounts);
78
- }
152
+ const [liquidityByAddress, chainData] = await Promise.all([
153
+ fetchMorphoVaultsLiquidity(network, [morphoVault]),
154
+ getMorphoVaultChainData(getBatchedViemProvider(provider, network), morphoVault, accounts),
155
+ ]);
156
+ const liquidityUnderlying = liquidityByAddress[morphoVault.address.toLowerCase()];
157
+ if (liquidityUnderlying === undefined) throw new Error(`Vault ${morphoVault.address} missing from Morpho API response`);
158
+ return formatMorphoVaultData(morphoVault, chainData, liquidityUnderlying, accounts);
159
+ }
@@ -147,6 +147,7 @@ export type MorphoMidnightAssetsData = { [key: string]: MorphoMidnightAssetData
147
147
 
148
148
  export interface MorphoMidnightMarketInfo {
149
149
  id: string,
150
+ isCreated: boolean, // markets are created lazily on first position; until then the view returns a zeroed struct (id = 0x0, no prices)
150
151
  loanToken: string,
151
152
  collaterals: string[], // collateral symbols, index-aligned with the market's collateral set
152
153
  maturity: number, // unix timestamp (seconds)