@defisaver/positions-sdk 2.1.166 → 2.1.168

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 (88) hide show
  1. package/cjs/aaveV2/index.js +8 -29
  2. package/cjs/aaveV3/index.js +2 -31
  3. package/cjs/aaveV4/index.d.ts +25 -0
  4. package/cjs/aaveV4/index.js +4 -1
  5. package/cjs/compoundV2/index.d.ts +1 -1
  6. package/cjs/compoundV2/index.js +2 -2
  7. package/cjs/curveUsd/index.d.ts +1 -1
  8. package/cjs/curveUsd/index.js +6 -1
  9. package/cjs/fluid/index.js +13 -12
  10. package/cjs/helpers/aaveBalances.d.ts +5 -0
  11. package/cjs/helpers/aaveBalances.js +51 -0
  12. package/cjs/helpers/fluidBalances.d.ts +6 -0
  13. package/cjs/helpers/fluidBalances.js +36 -0
  14. package/cjs/liquityV2/index.d.ts +8 -0
  15. package/cjs/liquityV2/index.js +3 -3
  16. package/cjs/llamaLend/index.d.ts +1 -1
  17. package/cjs/llamaLend/index.js +6 -1
  18. package/cjs/markets/morphoBlue/index.d.ts +0 -2
  19. package/cjs/markets/morphoBlue/index.js +3 -20
  20. package/cjs/morphoMidnight/index.d.ts +1 -1
  21. package/cjs/morphoMidnight/index.js +6 -1
  22. package/cjs/portfolio/index.d.ts +1 -0
  23. package/cjs/portfolio/index.js +3 -0
  24. package/cjs/portfolio/lendingSummaries.d.ts +7 -0
  25. package/cjs/portfolio/lendingSummaries.js +262 -0
  26. package/cjs/portfolio/lendingSummaryTransport.d.ts +8 -0
  27. package/cjs/portfolio/lendingSummaryTransport.js +109 -0
  28. package/cjs/spark/index.js +2 -31
  29. package/cjs/types/index.d.ts +1 -0
  30. package/cjs/types/index.js +1 -0
  31. package/cjs/types/lendingSummary.d.ts +34 -0
  32. package/cjs/types/lendingSummary.js +2 -0
  33. package/cjs/types/morphoBlue.d.ts +0 -1
  34. package/cjs/types/morphoBlue.js +0 -1
  35. package/esm/aaveV2/index.js +11 -32
  36. package/esm/aaveV3/index.js +3 -32
  37. package/esm/aaveV4/index.d.ts +25 -0
  38. package/esm/aaveV4/index.js +3 -1
  39. package/esm/compoundV2/index.d.ts +1 -1
  40. package/esm/compoundV2/index.js +2 -2
  41. package/esm/curveUsd/index.d.ts +1 -1
  42. package/esm/curveUsd/index.js +6 -1
  43. package/esm/fluid/index.js +13 -12
  44. package/esm/helpers/aaveBalances.d.ts +5 -0
  45. package/esm/helpers/aaveBalances.js +45 -0
  46. package/esm/helpers/fluidBalances.d.ts +6 -0
  47. package/esm/helpers/fluidBalances.js +28 -0
  48. package/esm/liquityV2/index.d.ts +8 -0
  49. package/esm/liquityV2/index.js +1 -1
  50. package/esm/llamaLend/index.d.ts +1 -1
  51. package/esm/llamaLend/index.js +6 -1
  52. package/esm/markets/morphoBlue/index.d.ts +0 -2
  53. package/esm/markets/morphoBlue/index.js +0 -16
  54. package/esm/morphoMidnight/index.d.ts +1 -1
  55. package/esm/morphoMidnight/index.js +6 -1
  56. package/esm/portfolio/index.d.ts +1 -0
  57. package/esm/portfolio/index.js +1 -0
  58. package/esm/portfolio/lendingSummaries.d.ts +7 -0
  59. package/esm/portfolio/lendingSummaries.js +256 -0
  60. package/esm/portfolio/lendingSummaryTransport.d.ts +8 -0
  61. package/esm/portfolio/lendingSummaryTransport.js +104 -0
  62. package/esm/spark/index.js +4 -33
  63. package/esm/types/index.d.ts +1 -0
  64. package/esm/types/index.js +1 -0
  65. package/esm/types/lendingSummary.d.ts +34 -0
  66. package/esm/types/lendingSummary.js +1 -0
  67. package/esm/types/morphoBlue.d.ts +0 -1
  68. package/esm/types/morphoBlue.js +0 -1
  69. package/package.json +1 -1
  70. package/src/aaveV2/index.ts +8 -48
  71. package/src/aaveV3/index.ts +2 -48
  72. package/src/aaveV4/index.ts +6 -1
  73. package/src/compoundV2/index.ts +2 -2
  74. package/src/curveUsd/index.ts +6 -1
  75. package/src/fluid/index.ts +13 -12
  76. package/src/helpers/aaveBalances.ts +41 -0
  77. package/src/helpers/fluidBalances.ts +34 -0
  78. package/src/liquityV2/index.ts +1 -1
  79. package/src/llamaLend/index.ts +6 -1
  80. package/src/markets/morphoBlue/index.ts +0 -16
  81. package/src/morphoMidnight/index.ts +6 -1
  82. package/src/portfolio/index.ts +2 -0
  83. package/src/portfolio/lendingSummaries.ts +216 -0
  84. package/src/portfolio/lendingSummaryTransport.ts +84 -0
  85. package/src/spark/index.ts +3 -49
  86. package/src/types/index.ts +2 -1
  87. package/src/types/lendingSummary.ts +41 -0
  88. package/src/types/morphoBlue.ts +0 -1
@@ -0,0 +1,256 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ /* global BigInt */
11
+ import Dec from 'decimal.js';
12
+ import { getAssetInfo, getAssetInfoByAddress } from '@defisaver/tokens';
13
+ import { custom, parseAbi, parseAbiItem, } from 'viem';
14
+ import { AaveMarkets, AaveV4Spokes, CompoundMarkets, compoundV2CollateralAssets, CrvUsdMarkets, LiquityV2Markets, LlamaLendMarkets, MorphoBlueMarkets, MorphoMidnightMarkets, SparkMarkets, } from '../markets';
15
+ import { AaveVersions, CompoundVersions } from '../types';
16
+ import { NetworkNumber, } from '../types/common';
17
+ import { getConfigContractAbi, getConfigContractAddress } from '../contracts';
18
+ import { getViemProvider } from '../services/viem';
19
+ import { getWrappedNativeAssetFromUnwrapped } from '../services/utils';
20
+ import { getAaveLikeBalances } from '../helpers/aaveBalances';
21
+ import { parseFluidBalances } from '../helpers/fluidBalances';
22
+ import { _getAaveV4LoanBalances } from '../aaveV4';
23
+ import { _getCompoundV2AccountBalances } from '../compoundV2';
24
+ import { _getCompoundV3AccountBalances } from '../compoundV3';
25
+ import { _getCrvUsdAccountBalances } from '../curveUsd';
26
+ import { _getLlamaLendAccountBalances } from '../llamaLend';
27
+ import { _getMorphoBlueAccountBalances } from '../morphoBlue';
28
+ import { _getMorphoMidnightAccountBalances } from '../morphoMidnight';
29
+ import { _getLiquityAccountBalances } from '../liquity';
30
+ import { _getUserCdps } from '../maker';
31
+ import { nftContractCreationBlockMapping } from '../liquityV2';
32
+ import { lendingSummaryTransport } from './lendingSummaryTransport';
33
+ const nftAbi = parseAbi([
34
+ 'function troveNFT() view returns (address)', 'function balanceOf(address) view returns (uint256)',
35
+ 'function ownerOf(uint256) view returns (address)',
36
+ ]);
37
+ const transfer = parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)');
38
+ const units = (value, decimals = 18) => new Dec(String(value)).div(new Dec(10).pow(decimals)).toString();
39
+ const positive = (value) => new Dec(String(value)).gt(0);
40
+ const supported = (list, network) => Object.values(list).filter(m => m.chainIds.includes(network));
41
+ /** Lending-only balances at one snapshot, valued with caller-supplied market prices.
42
+ * One shared client/limiter covers every wallet. Failed reads remain partial; cancellation
43
+ * discards results. Morpho Blue earn deposits, rewards and savings are excluded.
44
+ */
45
+ export function getWalletLendingSummaries(provider, network, walletAddresses, options) {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ var _a, _b, _c, _d, _e;
48
+ const addresses = [...new Set(walletAddresses.map(address => {
49
+ if (!/^0x[0-9a-f]{40}$/i.test(address))
50
+ throw new Error('Invalid wallet address');
51
+ return address.toLowerCase();
52
+ }))];
53
+ const summaries = Object.fromEntries(addresses.map(address => [address, {
54
+ status: 'complete', positions: [], protocols: [], suppliedUsd: '0', valuationComplete: true, errors: [],
55
+ }]));
56
+ if (!addresses.length || ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted))
57
+ return { summaries: {}, rateLimited: false };
58
+ const maxCalldataBytes = options.isSim ? 2000 : 32000;
59
+ const transport = lendingSummaryTransport(provider, options.signal, options.blockNumber, maxCalldataBytes);
60
+ const client = getViemProvider(transport.provider, network, {
61
+ transport: custom(transport.provider, { retryCount: 0 }), batch: { multicall: { batchSize: maxCalldataBytes } },
62
+ });
63
+ let snapshot;
64
+ try {
65
+ snapshot = (_b = options.blockNumber) !== null && _b !== void 0 ? _b : yield client.getBlockNumber();
66
+ transport.pinBlock(snapshot);
67
+ }
68
+ catch (error) {
69
+ if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted)
70
+ return { summaries: {}, rateLimited: transport.isRateLimited() };
71
+ for (const summary of Object.values(summaries)) {
72
+ summary.status = 'failed';
73
+ summary.errors.push(String(error));
74
+ }
75
+ return { summaries, rateLimited: transport.isRateLimited() };
76
+ }
77
+ const block = Number(snapshot);
78
+ // Dynamic ABI boundary for user-scoped CDP/NFT reads; money markets use their existing readers.
79
+ const read = (name, functionName, args = []) => client.readContract({
80
+ address: getConfigContractAddress(name, network, block), abi: getConfigContractAbi(name, network, block), functionName, args,
81
+ });
82
+ const nftRead = (address, functionName, args = []) => client.readContract({
83
+ address, abi: nftAbi, functionName, args,
84
+ });
85
+ const cache = new Map();
86
+ const shared = (key, fetch) => {
87
+ if (!cache.has(key))
88
+ cache.set(key, fetch());
89
+ return cache.get(key);
90
+ };
91
+ const tasks = [];
92
+ const tokens = new Set();
93
+ const valuations = [];
94
+ let prices = {};
95
+ const run = (address, protocol, key, work) => __awaiter(this, void 0, void 0, function* () {
96
+ var _a;
97
+ try {
98
+ if (!((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted))
99
+ yield work();
100
+ }
101
+ catch (error) {
102
+ summaries[address].errors.push(`${protocol}:${key}: ${String(error).split('\n')[0]}`);
103
+ }
104
+ });
105
+ const add = (address_1, protocol_1, key_1, balances_1, ...args_1) => __awaiter(this, [address_1, protocol_1, key_1, balances_1, ...args_1], void 0, function* (address, protocol, key, balances, human = false) {
106
+ const supply = Object.entries(balances.collateral || {}).concat(Object.entries(balances.deposited || {}));
107
+ const debt = Object.entries(balances.debt || {});
108
+ if (![...supply, ...debt].some(([, amount]) => positive(amount)))
109
+ return;
110
+ const entry = {
111
+ id: `${protocol}:${key}`,
112
+ protocol,
113
+ suppliedUsd: (supply.some(([, amount]) => positive(amount)) ? null : '0'),
114
+ debtUsd: (debt.some(([, amount]) => positive(amount)) ? null : '0'),
115
+ };
116
+ summaries[address].positions.push(entry);
117
+ const normalize = (amounts) => {
118
+ const result = {};
119
+ amounts.filter(([, amount]) => positive(amount)).forEach(([symbol, amount]) => {
120
+ const token = symbol.startsWith('0x') ? getAssetInfoByAddress(symbol, network) : getAssetInfo(getWrappedNativeAssetFromUnwrapped(symbol), network);
121
+ if (!token.address || !Number.isFinite(token.decimals))
122
+ throw new Error(`Token metadata unavailable: ${symbol}`);
123
+ const id = token.address.toLowerCase();
124
+ tokens.add(id);
125
+ result[id] = (result[id] || new Dec(0)).add(human ? amount : units(amount, token.decimals));
126
+ });
127
+ return result;
128
+ };
129
+ const amounts = [normalize(supply), normalize(debt)];
130
+ valuations.push(() => {
131
+ ['suppliedUsd', 'debtUsd'].forEach((field, i) => {
132
+ try {
133
+ entry[field] = Object.entries(amounts[i]).reduce((total, [token, amount]) => {
134
+ const price = new Dec(prices[token] || 0);
135
+ if (!price.isFinite() || !price.gt(0))
136
+ throw new Error(`Price unavailable: ${token}`);
137
+ return total.add(amount.mul(price));
138
+ }, new Dec(0)).toString();
139
+ }
140
+ catch (error) {
141
+ summaries[address].errors.push(`${entry.id}: ${String(error)}`);
142
+ }
143
+ });
144
+ });
145
+ });
146
+ const balanceTask = (address, protocol, key, fetch, human = false) => tasks.push(run(address, protocol, key, () => __awaiter(this, void 0, void 0, function* () { return add(address, protocol, key, yield fetch(), human); })));
147
+ for (const address of addresses) {
148
+ const aaveMarkets = supported(AaveMarkets(network), network).filter(m => [AaveVersions.AaveV2, AaveVersions.AaveV3, AaveVersions.AaveV3Lido, AaveVersions.AaveV3Etherfi].includes(m.value));
149
+ for (const market of [...aaveMarkets, ...supported(SparkMarkets(network), network)]) {
150
+ const v2 = market.value === AaveVersions.AaveV2;
151
+ const spark = !aaveMarkets.some(m => m.value === market.value);
152
+ balanceTask(address, spark ? 'spark' : v2 ? 'aaveV2' : 'aaveV3', market.value, () => getAaveLikeBalances(client, network, block, false, address, market, spark ? 'SparkView' : v2 ? 'AaveLoanInfoV2' : 'AaveV3View', market.assets.map(asset => getAssetInfo(getWrappedNativeAssetFromUnwrapped(asset), network).address)));
153
+ }
154
+ for (const spoke of supported(AaveV4Spokes(network), network)) {
155
+ balanceTask(address, 'aaveV4', spoke.value, () => __awaiter(this, void 0, void 0, function* () {
156
+ const { reserves } = yield _getAaveV4LoanBalances(client, network, block, address, spoke.address);
157
+ const balances = { collateral: {}, debt: {} };
158
+ reserves.forEach(r => {
159
+ balances.collateral[r.underlying] = new Dec(balances.collateral[r.underlying] || 0).add(r.supplied.toString()).toString();
160
+ balances.debt[r.underlying] = new Dec(balances.debt[r.underlying] || 0).add(r.totalDebt.toString()).toString();
161
+ });
162
+ return balances;
163
+ }));
164
+ }
165
+ for (const market of supported(CompoundMarkets(network), network)) {
166
+ const v2 = market.value === CompoundVersions.CompoundV2;
167
+ balanceTask(address, v2 ? 'compoundV2' : 'compoundV3', market.value, () => (v2
168
+ ? _getCompoundV2AccountBalances(client, network, block, false, address, compoundV2CollateralAssets.map(a => a.address))
169
+ : _getCompoundV3AccountBalances(client, network, block, false, address, market.baseMarketAddress)));
170
+ }
171
+ for (const market of supported(MorphoBlueMarkets(network), network))
172
+ balanceTask(address, 'morphoBlue', market.value, () => _getMorphoBlueAccountBalances(client, network, block, false, address, market), true);
173
+ for (const market of supported(MorphoMidnightMarkets(network), network))
174
+ balanceTask(address, 'morphoMidnight', market.value, () => _getMorphoMidnightAccountBalances(client, network, block, false, address, market, true), true);
175
+ if (network === NetworkNumber.Eth)
176
+ for (const market of supported(CrvUsdMarkets(network), network))
177
+ balanceTask(address, 'crvUsd', market.value, () => _getCrvUsdAccountBalances(client, network, block, false, address, market.controllerAddress, true));
178
+ if ([NetworkNumber.Eth, NetworkNumber.Arb].includes(network))
179
+ for (const market of supported(LlamaLendMarkets(network), network))
180
+ balanceTask(address, 'llamaLend', market.value, () => _getLlamaLendAccountBalances(client, network, block, false, address, market.controllerAddress, true));
181
+ if (network === NetworkNumber.Eth) {
182
+ balanceTask(address, 'liquity', 'trove', () => _getLiquityAccountBalances(client, network, block, false, address));
183
+ tasks.push(run(address, 'maker', 'discovery', () => __awaiter(this, void 0, void 0, function* () {
184
+ const cdps = yield _getUserCdps(client, network, address);
185
+ yield Promise.all(cdps.map(cdp => run(address, 'maker', String(cdp.id), () => __awaiter(this, void 0, void 0, function* () {
186
+ const [collateral, debt] = yield read('McdVat', 'urns', [cdp.ilk, cdp.urn]);
187
+ const rate = positive(debt) ? (yield shared(`maker:${cdp.ilk}`, () => read('McdVat', 'ilks', [cdp.ilk])))[1] : 0;
188
+ yield add(address, 'maker', String(cdp.id), { collateral: { [cdp.asset]: units(collateral) }, debt: { DAI: new Dec(units(debt)).mul(units(rate, 27)).toString() } }, true);
189
+ }))));
190
+ })));
191
+ for (const market of supported(LiquityV2Markets(network), network)) {
192
+ tasks.push(run(address, 'liquityV2', market.value, () => __awaiter(this, void 0, void 0, function* () {
193
+ const nft = yield shared(`nft:${market.value}`, () => nftRead(market.marketAddress, 'troveNFT'));
194
+ const count = yield nftRead(nft, 'balanceOf', [address]);
195
+ if (count === BigInt(0))
196
+ return;
197
+ const logs = yield client.getLogs({
198
+ address: nft, event: transfer, args: { to: address }, fromBlock: BigInt(nftContractCreationBlockMapping[market.value]), toBlock: snapshot,
199
+ });
200
+ const owned = (yield Promise.all([...new Set(logs.map(log => log.args.tokenId))].map((id) => __awaiter(this, void 0, void 0, function* () {
201
+ try {
202
+ return (yield nftRead(nft, 'ownerOf', [id])).toLowerCase() === address ? id : null;
203
+ }
204
+ catch (_a) {
205
+ return null;
206
+ }
207
+ })))).filter((id) => id !== null);
208
+ if (BigInt(owned.length) !== count)
209
+ summaries[address].errors.push(`liquityV2:${market.value}: Not all owned troves could be discovered`);
210
+ yield Promise.all(owned.map(id => run(address, 'liquityV2', `${market.value}:${id}`, () => __awaiter(this, void 0, void 0, function* () {
211
+ const data = yield read(market.isLegacy ? 'LiquityV2LegacyView' : 'LiquityV2View', 'getTroveInfo', [market.marketAddress, id]);
212
+ if (data.owner.toLowerCase() !== address)
213
+ throw new Error('Trove ownership changed');
214
+ yield add(address, 'liquityV2', `${market.value}:${id}`, { collateral: { [market.collateralToken]: data.collAmount.toString() }, debt: { [market.debtToken]: data.debtAmount.toString() } });
215
+ }))));
216
+ })));
217
+ }
218
+ }
219
+ if ([NetworkNumber.Eth, NetworkNumber.Arb, NetworkNumber.Base, NetworkNumber.Plasma].includes(network)) {
220
+ tasks.push(run(address, 'fluid', 'discovery', () => __awaiter(this, void 0, void 0, function* () {
221
+ const [positions, vaults] = yield read('FluidView', 'getUserPositions', [address]);
222
+ yield Promise.all(positions.map((p, i) => run(address, 'fluid', String(p.nftId), () => __awaiter(this, void 0, void 0, function* () {
223
+ if (positive(p.supply) || positive(p.borrow))
224
+ yield add(address, 'fluid', String(p.nftId), parseFluidBalances(p, vaults[i], network), true);
225
+ }))));
226
+ })));
227
+ }
228
+ }
229
+ yield Promise.all(tasks);
230
+ if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted)
231
+ return { summaries: {}, rateLimited: transport.isRateLimited() };
232
+ if (tokens.size) {
233
+ try {
234
+ prices = yield options.resolvePrices(network, [...tokens], options.signal);
235
+ }
236
+ catch (error) {
237
+ for (const summary of Object.values(summaries))
238
+ if (summary.positions.length)
239
+ summary.errors.push(`Prices: ${String(error)}`);
240
+ }
241
+ }
242
+ if ((_e = options.signal) === null || _e === void 0 ? void 0 : _e.aborted)
243
+ return { summaries: {}, rateLimited: transport.isRateLimited() };
244
+ valuations.forEach(value => value());
245
+ for (const summary of Object.values(summaries)) {
246
+ summary.positions.sort((a, b) => a.id.localeCompare(b.id));
247
+ summary.protocols = [...new Set(summary.positions.map(p => p.protocol))];
248
+ summary.suppliedUsd = summary.positions.reduce((total, p) => total.add(p.suppliedUsd || 0), new Dec(0)).toString();
249
+ summary.valuationComplete = summary.positions.every(p => p.suppliedUsd !== null && p.debtUsd !== null);
250
+ summary.errors = [...new Set(summary.errors)];
251
+ if (summary.errors.length)
252
+ summary.status = 'partial';
253
+ }
254
+ return { summaries, rateLimited: transport.isRateLimited() };
255
+ });
256
+ }
@@ -0,0 +1,8 @@
1
+ import { EthereumProvider } from '../types/common';
2
+ export declare const isLendingSummaryRateLimit: (error: unknown) => boolean;
3
+ /** One limiter for all reads, including split multicalls. No retries after cancellation/429. */
4
+ export declare function lendingSummaryTransport(provider: EthereumProvider, signal?: AbortSignal, blockNumber?: bigint, maxCalldataBytes?: number): {
5
+ provider: EthereumProvider;
6
+ isRateLimited: () => boolean;
7
+ pinBlock: (value: bigint) => void;
8
+ };
@@ -0,0 +1,104 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { decodeFunctionData, decodeFunctionResult, encodeFunctionData, encodeFunctionResult, multicall3Abi, } from 'viem';
11
+ const errorText = (error) => {
12
+ const detail = error;
13
+ return `${(detail === null || detail === void 0 ? void 0 : detail.message) || String(error)} ${(detail === null || detail === void 0 ? void 0 : detail.code) || ''} ${(detail === null || detail === void 0 ? void 0 : detail.status) || ''}`;
14
+ };
15
+ const logRangeLimit = (error) => /block range|too many (results|logs)|query returned|response.*size|range.*limit/i.test(errorText(error));
16
+ const oversized = (error) => /413|request.*(large|size)|response.*(large|size)|out of gas|gas (required|limit)|exceeds.*gas|execution.*limit/i.test(errorText(error));
17
+ export const isLendingSummaryRateLimit = (error) => !oversized(error) && !logRangeLimit(error) && /429|rate.?limit|too many requests|compute units|limit exceeded/i.test(errorText(error));
18
+ /** One limiter for all reads, including split multicalls. No retries after cancellation/429. */
19
+ export function lendingSummaryTransport(provider, signal, blockNumber, maxCalldataBytes = 32000) {
20
+ let pinnedBlock = blockNumber;
21
+ let active = 0;
22
+ let rateLimit;
23
+ const waiting = [];
24
+ const check = () => {
25
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
26
+ throw new Error('Lending summary cancelled');
27
+ // Keep the provider's original error code/message, including plain RPC error objects.
28
+ // eslint-disable-next-line @typescript-eslint/no-throw-literal
29
+ if (rateLimit !== undefined)
30
+ throw rateLimit;
31
+ };
32
+ const send = (args) => __awaiter(this, void 0, void 0, function* () {
33
+ if (active >= 4)
34
+ yield new Promise(resolve => { waiting.push(resolve); });
35
+ else
36
+ active++;
37
+ try {
38
+ check();
39
+ return yield provider.request(args);
40
+ }
41
+ catch (error) {
42
+ if (isLendingSummaryRateLimit(error))
43
+ rateLimit = error;
44
+ throw error;
45
+ }
46
+ finally {
47
+ const next = waiting.shift();
48
+ if (next)
49
+ next();
50
+ else
51
+ active--;
52
+ }
53
+ });
54
+ const request = (args) => __awaiter(this, void 0, void 0, function* () {
55
+ var _a;
56
+ check();
57
+ const params = [...(args.params || [])];
58
+ if (pinnedBlock !== undefined) {
59
+ const block = `0x${pinnedBlock.toString(16)}`;
60
+ if (args.method === 'eth_blockNumber')
61
+ return block;
62
+ if (['eth_call', 'eth_getCode'].includes(args.method))
63
+ params[1] = block;
64
+ }
65
+ const call = params[0];
66
+ const isMulticall = args.method === 'eth_call' && ((_a = call === null || call === void 0 ? void 0 : call.data) === null || _a === void 0 ? void 0 : _a.startsWith('0x82ad56cb'));
67
+ const splitMulticall = (error) => __awaiter(this, void 0, void 0, function* () {
68
+ const { args: [calls] } = decodeFunctionData({ abi: multicall3Abi, data: call.data });
69
+ if (!calls || calls.length < 2)
70
+ throw error;
71
+ // Sequential halves keep the same concurrency bound and retain per-call failures.
72
+ const results = [];
73
+ for (const half of [calls.slice(0, Math.ceil(calls.length / 2)), calls.slice(Math.ceil(calls.length / 2))]) {
74
+ const data = encodeFunctionData({ abi: multicall3Abi, functionName: 'aggregate3', args: [half] });
75
+ const encoded = yield request(Object.assign(Object.assign({}, args), { params: [Object.assign(Object.assign({}, call), { data }), ...params.slice(1)] }));
76
+ results.push(...decodeFunctionResult({ abi: multicall3Abi, functionName: 'aggregate3', data: encoded }));
77
+ }
78
+ return encodeFunctionResult({ abi: multicall3Abi, functionName: 'aggregate3', result: results });
79
+ });
80
+ // Viem's batch size counts inner calls only. Also bound the fully encoded calldata.
81
+ if (isMulticall && (call.data.length - 2) / 2 > maxCalldataBytes)
82
+ return splitMulticall(new Error('Single call exceeds summary calldata limit'));
83
+ try {
84
+ return yield send(Object.assign(Object.assign({}, args), { params }));
85
+ }
86
+ catch (error) {
87
+ check();
88
+ if (args.method === 'eth_getLogs' && logRangeLimit(error)) {
89
+ const from = BigInt(call.fromBlock);
90
+ const to = BigInt(call.toBlock);
91
+ if (from >= to)
92
+ throw error;
93
+ const middle = (from + to) / BigInt(2);
94
+ const first = yield request(Object.assign(Object.assign({}, args), { params: [Object.assign(Object.assign({}, call), { toBlock: `0x${middle.toString(16)}` })] }));
95
+ const last = yield request(Object.assign(Object.assign({}, args), { params: [Object.assign(Object.assign({}, call), { fromBlock: `0x${(middle + BigInt(1)).toString(16)}` })] }));
96
+ return [...first, ...last];
97
+ }
98
+ if (!isMulticall || !oversized(error))
99
+ throw error;
100
+ return splitMulticall(error);
101
+ }
102
+ });
103
+ return { provider: { request }, isRateLimited: () => rateLimit !== undefined, pinBlock: (value) => { pinnedBlock = value; } };
104
+ }
@@ -9,14 +9,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import Dec from 'decimal.js';
11
11
  import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
12
+ import { getAaveLikeBalances } from '../helpers/aaveBalances';
12
13
  import { IncentiveKind, } from '../types/common';
13
- import { ethToWeth, wethToEth, wethToEthByAddress, } from '../services/utils';
14
+ import { ethToWeth, } from '../services/utils';
14
15
  import { calculateNetApy, getStakingApy, STAKING_ASSETS, } from '../staking';
15
16
  import { SparkViewContractViem, SparkIncentiveDataProviderContractViem, createViemContractFromConfigFunc, } from '../contracts';
16
17
  import { sparkGetAggregatedPositionData, sparkIsInIsolationMode } from '../helpers/sparkHelpers';
17
18
  import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
18
19
  import { SPARK_V1 } from '../markets/spark';
19
- import { getViemProvider, setViemBlockNumber } from '../services/viem';
20
+ import { getViemProvider } from '../services/viem';
20
21
  export const sparkEmodeCategoriesMapping = (extractedState, usedAssets) => {
21
22
  const { assetsData } = extractedState;
22
23
  const usedAssetsValues = Object.values(usedAssets);
@@ -228,37 +229,7 @@ export const EMPTY_SPARK_DATA = {
228
229
  exposure: 'N/A',
229
230
  };
230
231
  export const _getSparkAccountBalances = (provider, network, block, addressMapping, address) => __awaiter(void 0, void 0, void 0, function* () {
231
- let balances = {
232
- collateral: {},
233
- debt: {},
234
- };
235
- if (!address) {
236
- return balances;
237
- }
238
- const loanInfoContract = SparkViewContractViem(provider, network, block);
239
- const market = SPARK_V1(network);
240
- const marketAddress = market.providerAddress;
241
- // @ts-ignore
242
- const protocolDataProviderContract = createViemContractFromConfigFunc(market.protocolData, market.protocolDataAddress)(provider, network);
243
- // @ts-ignore
244
- const reserveTokens = yield protocolDataProviderContract.read.getAllReservesTokens(setViemBlockNumber(block));
245
- const symbols = reserveTokens.map(({ symbol }) => symbol);
246
- const _addresses = reserveTokens.map(({ tokenAddress }) => tokenAddress);
247
- // split addresses in half to avoid gas limit by multicall
248
- const middleAddressIndex = Math.floor(_addresses.length / 2);
249
- const [tokenBalances1, tokenBalances2] = yield Promise.all([
250
- loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex)], setViemBlockNumber(block)),
251
- loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)], setViemBlockNumber(block)),
252
- ]);
253
- const loanInfo = [...tokenBalances1, ...tokenBalances2];
254
- loanInfo.forEach((tokenInfo, i) => {
255
- const asset = wethToEth(symbols[i]);
256
- const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
257
- balances = {
258
- collateral: Object.assign(Object.assign({}, balances.collateral), { [addressMapping ? assetAddr : asset]: tokenInfo.balance.toString() }),
259
- debt: Object.assign(Object.assign({}, balances.debt), { [addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString() }),
260
- };
261
- });
232
+ const balances = yield getAaveLikeBalances(provider, network, block, addressMapping, address, SPARK_V1(network), 'SparkView');
262
233
  return balances;
263
234
  });
264
235
  export const getSparkAccountBalances = (provider, network, block, addressMapping, address) => __awaiter(void 0, void 0, void 0, function* () { return _getSparkAccountBalances(getViemProvider(provider, network, { batch: { multicall: true } }), network, block, addressMapping, address); });
@@ -15,3 +15,4 @@ export * from './merkl';
15
15
  export * from './savings';
16
16
  export * from './common';
17
17
  export * from './aaveV4';
18
+ export * from './lendingSummary';
@@ -15,3 +15,4 @@ export * from './merkl';
15
15
  export * from './savings';
16
16
  export * from './common';
17
17
  export * from './aaveV4';
18
+ export * from './lendingSummary';
@@ -0,0 +1,34 @@
1
+ import { EthAddress, NetworkNumber } from './common';
2
+ export type LendingSummaryPosition = {
3
+ id: string;
4
+ protocol: string;
5
+ /** Estimated decimal USD values; null means unavailable, never a verified zero. */
6
+ suppliedUsd: string | null;
7
+ debtUsd: string | null;
8
+ };
9
+ export type WalletLendingSummary = {
10
+ status: 'complete' | 'partial' | 'failed';
11
+ positions: LendingSummaryPosition[];
12
+ protocols: string[];
13
+ /** Sum of known supply values; check valuationComplete before ranking by value. */
14
+ suppliedUsd: string;
15
+ valuationComplete: boolean;
16
+ errors: string[];
17
+ };
18
+ /** Resolve distinct token addresses to USD prices keyed by lowercase address.
19
+ * Native tokens use their wrapped address. Missing/invalid prices remain unavailable.
20
+ * Prices are current market estimates; balances may come from a historical/fork snapshot.
21
+ */
22
+ export type LendingSummaryPriceResolver = (network: NetworkNumber, tokens: EthAddress[], signal?: AbortSignal) => Promise<Record<string, string>>;
23
+ export type LendingSummaryOptions = {
24
+ resolvePrices: LendingSummaryPriceResolver;
25
+ signal?: AbortSignal;
26
+ /** Defaults to a snapshot of the provider's latest block. */
27
+ blockNumber?: bigint;
28
+ /** Use the smaller 2 KB calldata limit required by simulation providers. */
29
+ isSim?: boolean;
30
+ };
31
+ export type WalletLendingSummaries = {
32
+ summaries: Record<string, WalletLendingSummary>;
33
+ rateLimited: boolean;
34
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -2,7 +2,6 @@ import { EthAddress, IncentiveData, LeverageType, MMUsedAssets, NetworkNumber }
2
2
  export declare enum MorphoBlueVersions {
3
3
  MorphoBlueMKRDAI_777 = "morphobluemkrdai_777",// MKR/DAI
4
4
  MorphoBlueWoEthEth_860 = "morphobluewoetheth_860",// woETH/ETH
5
- MorphoBlueOsEthEth_860 = "morphoblueosetheth_860",// osETH/ETH
6
5
  MorphoBlueWeEthEth_860 = "morphoblueweetheth_860",// weETH/ETH
7
6
  MorphoBlueWstEthUSDC = "morphobluewstethusdc",// wstETH/USDC
8
7
  MorphoBlueSDAIUSDC = "morphobluesdaiusdc",// sDAI/USDC
@@ -3,7 +3,6 @@ export var MorphoBlueVersions;
3
3
  // MAINNET
4
4
  MorphoBlueVersions["MorphoBlueMKRDAI_777"] = "morphobluemkrdai_777";
5
5
  MorphoBlueVersions["MorphoBlueWoEthEth_860"] = "morphobluewoetheth_860";
6
- MorphoBlueVersions["MorphoBlueOsEthEth_860"] = "morphoblueosetheth_860";
7
6
  MorphoBlueVersions["MorphoBlueWeEthEth_860"] = "morphoblueweetheth_860";
8
7
  MorphoBlueVersions["MorphoBlueWstEthUSDC"] = "morphobluewstethusdc";
9
8
  MorphoBlueVersions["MorphoBlueSDAIUSDC"] = "morphobluesdaiusdc";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defisaver/positions-sdk",
3
- "version": "2.1.166",
3
+ "version": "2.1.168",
4
4
  "description": "",
5
5
  "main": "./cjs/index.js",
6
6
  "module": "./esm/index.js",
@@ -1,12 +1,13 @@
1
1
  import Dec from 'decimal.js';
2
2
  import { assetAmountInEth, getAssetInfo } from '@defisaver/tokens';
3
3
  import { Client } from 'viem';
4
+ import { getAaveLikeBalances } from '../helpers/aaveBalances';
4
5
  import {
5
6
  Blockish, EthAddress, EthereumProvider, IncentiveKind, NetworkNumber, PositionBalances,
6
7
  } from '../types/common';
7
8
  import { calculateNetApy, getStakingApy } from '../staking';
8
- import { ethToWeth, wethToEth, wethToEthByAddress } from '../services/utils';
9
- import { AaveLoanInfoV2ContractViem, createViemContractFromConfigFunc } from '../contracts';
9
+ import { ethToWeth, wethToEth } from '../services/utils';
10
+ import { AaveLoanInfoV2ContractViem } from '../contracts';
10
11
  import { aprToApy, calculateBorrowingAssetLimit } from '../moneymarket';
11
12
  import {
12
13
  AaveMarketInfo, AaveV2AssetData, AaveV2AssetsData, AaveV2PositionData, AaveV2UsedAsset, AaveV2UsedAssets,
@@ -89,52 +90,11 @@ export const _getAaveV2MarketsData = async (provider: Client, network: NetworkNu
89
90
  export const getAaveV2MarketsData = async (provider: EthereumProvider, network: NetworkNumber, selectedMarket: AaveMarketInfo) => _getAaveV2MarketsData(getViemProvider(provider, network), network, selectedMarket);
90
91
 
91
92
  export const _getAaveV2AccountBalances = async (provider: Client, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
92
- let balances: PositionBalances = {
93
- collateral: {},
94
- debt: {},
95
- };
96
-
97
- if (!address) {
98
- return balances;
99
- }
100
-
101
- const market = AAVE_V2;
102
-
103
- const loanInfoContract = AaveLoanInfoV2ContractViem(provider, network, block);
104
-
105
- const marketAddress = market.providerAddress;
106
- // @ts-ignore
107
- const protocolDataProviderContract = createViemContractFromConfigFunc(market.protocolData, market.protocolDataAddress)(provider, network);
108
-
109
- // @ts-ignore
110
- const reserveTokens = await protocolDataProviderContract.read.getAllReservesTokens(setViemBlockNumber(block)) as { symbol: string, tokenAddress: EthAddress }[];
111
- const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
112
- const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
113
-
114
- const loanInfo = await loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses as EthAddress[]], setViemBlockNumber(block));
115
-
116
- loanInfo.forEach((_tokenInfo: any, i: number) => {
117
- const asset = wethToEth(symbols[i]);
118
- const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
119
- const tokenInfo = { ..._tokenInfo };
120
-
121
- // known bug: stETH leaves 1 wei on every transfer
122
- if (asset === 'stETH' && tokenInfo.balance.toString() === '1') {
123
- tokenInfo.balance = '0';
124
- }
125
-
126
- balances = {
127
- collateral: {
128
- ...balances.collateral,
129
- [addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
130
- },
131
- debt: {
132
- ...balances.debt,
133
- [addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
134
- },
135
- };
136
- });
137
-
93
+ const balances = await getAaveLikeBalances(provider, network, block, addressMapping, address, AAVE_V2, 'AaveLoanInfoV2');
94
+ if (!address) return balances;
95
+ // Preserve the legacy getter's stETH transfer-dust convention.
96
+ const key = addressMapping ? getAssetInfo('stETH', network).address.toLowerCase() : 'stETH';
97
+ if (balances.collateral?.[key] === '1') balances.collateral[key] = '0';
138
98
  return balances;
139
99
  };
140
100
 
@@ -1,6 +1,7 @@
1
1
  import { assetAmountInEth, assetAmountInWei, getAssetInfo } from '@defisaver/tokens';
2
2
  import { Client } from 'viem';
3
3
  import Dec from 'decimal.js';
4
+ import { getAaveLikeBalances } from '../helpers/aaveBalances';
4
5
  import {
5
6
  AaveIncentiveDataProviderV3ContractViem,
6
7
  AaveIncentivesControllerViem,
@@ -17,7 +18,6 @@ import {
17
18
  isEnabledOnBitmap,
18
19
  isLayer2Network,
19
20
  wethToEth,
20
- wethToEthByAddress,
21
21
  } from '../services/utils';
22
22
  import { getStakingApy, STAKING_ASSETS } from '../staking';
23
23
  import {
@@ -384,53 +384,7 @@ export const EMPTY_AAVE_DATA = {
384
384
  };
385
385
 
386
386
  export const _getAaveV3AccountBalances = async (provider: Client, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress): Promise<PositionBalances> => {
387
- let balances: PositionBalances = {
388
- collateral: {},
389
- debt: {},
390
- };
391
-
392
- if (!address) {
393
- return balances;
394
- }
395
-
396
- const loanInfoContract = AaveV3ViewContractViem(provider, network, block);
397
-
398
- const market = AAVE_V3(network);
399
- const marketAddress = market.providerAddress;
400
- // @ts-ignore
401
- const protocolDataProviderContract = createViemContractFromConfigFunc(market.protocolData, market.protocolDataAddress)(provider, network);
402
-
403
- // @ts-ignore
404
- const reserveTokens = await protocolDataProviderContract.read.getAllReservesTokens(setViemBlockNumber(block)) as { symbol: string, tokenAddress: EthAddress }[];
405
- const symbols = reserveTokens.map(({ symbol }: { symbol: string }) => symbol);
406
- const _addresses = reserveTokens.map(({ tokenAddress }: { tokenAddress: EthAddress }) => tokenAddress);
407
-
408
- // split addresses in half to avoid gas limit by multicall
409
- const middleAddressIndex = Math.floor(_addresses.length / 2);
410
-
411
- const [tokenBalances1, tokenBalances2] = await Promise.all([
412
- loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(0, middleAddressIndex)], setViemBlockNumber(block)),
413
- loanInfoContract.read.getTokenBalances([marketAddress, address, _addresses.slice(middleAddressIndex, _addresses.length)], setViemBlockNumber(block)),
414
- ]);
415
-
416
- const loanInfo = [...tokenBalances1, ...tokenBalances2];
417
-
418
- loanInfo.forEach((tokenInfo: any, i: number) => {
419
- const asset = wethToEth(symbols[i]);
420
- const assetAddr = wethToEthByAddress(_addresses[i], network).toLowerCase();
421
-
422
- balances = {
423
- collateral: {
424
- ...balances.collateral,
425
- [addressMapping ? assetAddr : asset]: tokenInfo.balance.toString(),
426
- },
427
- debt: {
428
- ...balances.debt,
429
- [addressMapping ? assetAddr : asset]: new Dec(tokenInfo.borrowsStable.toString()).add(tokenInfo.borrowsVariable.toString()).toString(),
430
- },
431
- };
432
- });
433
-
387
+ const balances = await getAaveLikeBalances(provider, network, block, addressMapping, address, AAVE_V3(network), 'AaveV3View');
434
388
  return balances;
435
389
  };
436
390