@defisaver/positions-sdk 2.1.174 → 2.1.175-looping-2-dev-dev
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.
- package/cjs/aaveV2/index.d.ts +4 -4
- package/cjs/aaveV2/index.js +7 -7
- package/cjs/aaveV3/index.d.ts +5 -14
- package/cjs/aaveV3/index.js +14 -10
- package/cjs/aaveV3/merkl.d.ts +5 -1
- package/cjs/aaveV3/merkl.js +8 -3
- package/cjs/aaveV3/sgho.d.ts +2 -16
- package/cjs/aaveV4/index.d.ts +4 -3
- package/cjs/aaveV4/index.js +19 -16
- package/cjs/aaveV4/lend.d.ts +2 -43
- package/cjs/aaveV4/merkl.d.ts +10 -2
- package/cjs/aaveV4/merkl.js +15 -6
- package/cjs/claiming/aaveV3.d.ts +3 -3
- package/cjs/claiming/aaveV3.js +5 -4
- package/cjs/claiming/ethena.d.ts +2 -1
- package/cjs/claiming/king.d.ts +3 -2
- package/cjs/claiming/king.js +3 -2
- package/cjs/claiming/spark.d.ts +4 -4
- package/cjs/claiming/spark.js +8 -7
- package/cjs/claiming/uniswap.d.ts +2 -2
- package/cjs/claiming/uniswap.js +3 -2
- package/cjs/compoundV2/index.d.ts +4 -4
- package/cjs/compoundV2/index.js +9 -9
- package/cjs/compoundV3/index.d.ts +5 -4
- package/cjs/compoundV3/index.js +17 -13
- package/cjs/compoundV3/merkl.d.ts +1 -1
- package/cjs/compoundV3/merkl.js +2 -5
- package/cjs/curveUsd/index.d.ts +5 -5
- package/cjs/curveUsd/index.js +17 -17
- package/cjs/fluid/index.d.ts +23 -66
- package/cjs/fluid/index.js +75 -72
- package/cjs/fluid/merkl.d.ts +5 -3
- package/cjs/fluid/merkl.js +11 -6
- package/cjs/helpers/aaveHelpers/index.js +1 -1
- package/cjs/helpers/aaveV4Helpers/index.js +14 -2
- package/cjs/helpers/compoundHelpers/index.js +2 -2
- package/cjs/helpers/curveUsdHelpers/index.js +1 -1
- package/cjs/helpers/fluidHelpers/index.js +1 -1
- package/cjs/helpers/liquityV2Helpers/index.js +1 -1
- package/cjs/helpers/llamaLendHelpers/index.js +1 -1
- package/cjs/helpers/morphoBlueHelpers/index.js +1 -1
- package/cjs/helpers/morphoMidnightHelpers/index.js +1 -1
- package/cjs/helpers/sparkHelpers/index.js +1 -1
- package/cjs/liquity/index.d.ts +5 -15
- package/cjs/liquity/index.js +23 -23
- package/cjs/liquityV2/index.d.ts +16 -31
- package/cjs/liquityV2/index.js +96 -78
- package/cjs/llamaLend/index.d.ts +5 -5
- package/cjs/llamaLend/index.js +13 -13
- package/cjs/maker/index.d.ts +6 -6
- package/cjs/maker/index.js +16 -16
- package/cjs/moneymarket/moneymarketCommonService.js +13 -2
- package/cjs/morphoBlue/index.d.ts +7 -7
- package/cjs/morphoBlue/index.js +28 -26
- package/cjs/morphoBlue/merkl.d.ts +5 -3
- package/cjs/morphoBlue/merkl.js +6 -8
- package/cjs/morphoMidnight/index.d.ts +5 -5
- package/cjs/morphoMidnight/index.js +18 -18
- package/cjs/portfolio/customDeFiData.d.ts +3 -0
- package/cjs/portfolio/customDeFiData.js +267 -0
- package/cjs/portfolio/index.d.ts +17 -8
- package/cjs/portfolio/index.js +459 -520
- package/cjs/portfolio/lendingProtocols.d.ts +184 -0
- package/cjs/portfolio/lendingProtocols.js +196 -0
- package/cjs/savings/index.d.ts +8 -2
- package/cjs/savings/index.js +33 -4
- package/cjs/services/merkl.d.ts +46 -2
- package/cjs/services/merkl.js +190 -19
- package/cjs/services/priceService.d.ts +12 -12
- package/cjs/services/priceService.js +30 -29
- package/cjs/services/viem.d.ts +10 -2
- package/cjs/services/viem.js +27 -1
- package/cjs/spark/index.d.ts +4 -4
- package/cjs/spark/index.js +9 -9
- package/cjs/types/aave.d.ts +98 -2
- package/cjs/types/aaveV4.d.ts +45 -0
- package/cjs/types/common.d.ts +1 -0
- package/cjs/types/common.js +1 -0
- package/cjs/types/compound.d.ts +26 -2
- package/cjs/types/curveUsd.d.ts +9 -1
- package/cjs/types/fluid.d.ts +13 -0
- package/cjs/types/index.d.ts +1 -0
- package/cjs/types/index.js +1 -0
- package/cjs/types/liquity.d.ts +12 -0
- package/cjs/types/liquityV2.d.ts +24 -0
- package/cjs/types/llamaLend.d.ts +12 -1
- package/cjs/types/merkl.d.ts +18 -0
- package/cjs/types/morphoBlue.d.ts +2 -0
- package/cjs/types/portfolio.d.ts +162 -5
- package/cjs/types/portfolio.js +18 -0
- package/cjs/types/savings/index.d.ts +9 -1
- package/cjs/types/spark.d.ts +21 -1
- package/cjs/umbrella/index.d.ts +3 -4
- package/cjs/umbrella/index.js +5 -4
- package/esm/aaveV2/index.d.ts +4 -4
- package/esm/aaveV2/index.js +8 -8
- package/esm/aaveV3/index.d.ts +5 -14
- package/esm/aaveV3/index.js +15 -11
- package/esm/aaveV3/merkl.d.ts +5 -1
- package/esm/aaveV3/merkl.js +9 -4
- package/esm/aaveV3/sgho.d.ts +2 -16
- package/esm/aaveV4/index.d.ts +4 -3
- package/esm/aaveV4/index.js +20 -17
- package/esm/aaveV4/lend.d.ts +2 -43
- package/esm/aaveV4/merkl.d.ts +10 -2
- package/esm/aaveV4/merkl.js +16 -7
- package/esm/claiming/aaveV3.d.ts +3 -3
- package/esm/claiming/aaveV3.js +6 -5
- package/esm/claiming/ethena.d.ts +2 -1
- package/esm/claiming/king.d.ts +3 -2
- package/esm/claiming/king.js +3 -2
- package/esm/claiming/spark.d.ts +4 -4
- package/esm/claiming/spark.js +9 -8
- package/esm/claiming/uniswap.d.ts +2 -2
- package/esm/claiming/uniswap.js +3 -2
- package/esm/compoundV2/index.d.ts +4 -4
- package/esm/compoundV2/index.js +9 -9
- package/esm/compoundV3/index.d.ts +5 -4
- package/esm/compoundV3/index.js +19 -15
- package/esm/compoundV3/merkl.d.ts +1 -1
- package/esm/compoundV3/merkl.js +3 -6
- package/esm/curveUsd/index.d.ts +5 -5
- package/esm/curveUsd/index.js +17 -17
- package/esm/fluid/index.d.ts +23 -66
- package/esm/fluid/index.js +76 -73
- package/esm/fluid/merkl.d.ts +5 -3
- package/esm/fluid/merkl.js +12 -7
- package/esm/helpers/aaveHelpers/index.js +1 -1
- package/esm/helpers/aaveV4Helpers/index.js +15 -3
- package/esm/helpers/compoundHelpers/index.js +2 -2
- package/esm/helpers/curveUsdHelpers/index.js +1 -1
- package/esm/helpers/fluidHelpers/index.js +1 -1
- package/esm/helpers/liquityV2Helpers/index.js +1 -1
- package/esm/helpers/llamaLendHelpers/index.js +1 -1
- package/esm/helpers/morphoBlueHelpers/index.js +1 -1
- package/esm/helpers/morphoMidnightHelpers/index.js +1 -1
- package/esm/helpers/sparkHelpers/index.js +1 -1
- package/esm/liquity/index.d.ts +5 -15
- package/esm/liquity/index.js +23 -23
- package/esm/liquityV2/index.d.ts +16 -31
- package/esm/liquityV2/index.js +95 -78
- package/esm/llamaLend/index.d.ts +5 -5
- package/esm/llamaLend/index.js +13 -13
- package/esm/maker/index.d.ts +6 -6
- package/esm/maker/index.js +16 -16
- package/esm/moneymarket/moneymarketCommonService.js +13 -2
- package/esm/morphoBlue/index.d.ts +7 -7
- package/esm/morphoBlue/index.js +29 -27
- package/esm/morphoBlue/merkl.d.ts +5 -3
- package/esm/morphoBlue/merkl.js +7 -9
- package/esm/morphoMidnight/index.d.ts +5 -5
- package/esm/morphoMidnight/index.js +18 -18
- package/esm/portfolio/customDeFiData.d.ts +3 -0
- package/esm/portfolio/customDeFiData.js +261 -0
- package/esm/portfolio/index.d.ts +17 -8
- package/esm/portfolio/index.js +459 -522
- package/esm/portfolio/lendingProtocols.d.ts +184 -0
- package/esm/portfolio/lendingProtocols.js +189 -0
- package/esm/savings/index.d.ts +8 -2
- package/esm/savings/index.js +31 -3
- package/esm/services/merkl.d.ts +46 -2
- package/esm/services/merkl.js +180 -18
- package/esm/services/priceService.d.ts +12 -12
- package/esm/services/priceService.js +31 -30
- package/esm/services/viem.d.ts +10 -2
- package/esm/services/viem.js +25 -0
- package/esm/spark/index.d.ts +4 -4
- package/esm/spark/index.js +10 -10
- package/esm/types/aave.d.ts +98 -2
- package/esm/types/aaveV4.d.ts +45 -0
- package/esm/types/common.d.ts +1 -0
- package/esm/types/common.js +1 -0
- package/esm/types/compound.d.ts +26 -2
- package/esm/types/curveUsd.d.ts +9 -1
- package/esm/types/fluid.d.ts +13 -0
- package/esm/types/index.d.ts +1 -0
- package/esm/types/index.js +1 -0
- package/esm/types/liquity.d.ts +12 -0
- package/esm/types/liquityV2.d.ts +24 -0
- package/esm/types/llamaLend.d.ts +12 -1
- package/esm/types/merkl.d.ts +18 -0
- package/esm/types/morphoBlue.d.ts +2 -0
- package/esm/types/portfolio.d.ts +162 -5
- package/esm/types/portfolio.js +17 -1
- package/esm/types/savings/index.d.ts +9 -1
- package/esm/types/spark.d.ts +21 -1
- package/esm/umbrella/index.d.ts +3 -4
- package/esm/umbrella/index.js +5 -4
- package/package.json +1 -1
- package/src/aaveV2/index.ts +7 -7
- package/src/aaveV3/index.ts +16 -11
- package/src/aaveV3/merkl.ts +9 -4
- package/src/aaveV3/sgho.ts +2 -17
- package/src/aaveV4/index.ts +19 -16
- package/src/aaveV4/lend.ts +2 -48
- package/src/aaveV4/merkl.ts +16 -7
- package/src/claiming/aaveV3.ts +9 -5
- package/src/claiming/ethena.ts +5 -5
- package/src/claiming/king.ts +8 -5
- package/src/claiming/spark.ts +15 -10
- package/src/claiming/uniswap.ts +4 -3
- package/src/compoundV2/index.ts +10 -9
- package/src/compoundV3/index.ts +20 -14
- package/src/compoundV3/merkl.ts +5 -4
- package/src/curveUsd/index.ts +19 -17
- package/src/fluid/index.ts +91 -72
- package/src/fluid/merkl.ts +12 -7
- package/src/helpers/aaveHelpers/index.ts +1 -1
- package/src/helpers/aaveV4Helpers/index.ts +16 -2
- package/src/helpers/compoundHelpers/index.ts +2 -2
- package/src/helpers/curveUsdHelpers/index.ts +1 -1
- package/src/helpers/fluidHelpers/index.ts +1 -1
- package/src/helpers/liquityV2Helpers/index.ts +1 -1
- package/src/helpers/llamaLendHelpers/index.ts +1 -1
- package/src/helpers/morphoBlueHelpers/index.ts +1 -1
- package/src/helpers/morphoMidnightHelpers/index.ts +1 -1
- package/src/helpers/sparkHelpers/index.ts +1 -1
- package/src/liquity/index.ts +24 -24
- package/src/liquityV2/index.ts +110 -76
- package/src/llamaLend/index.ts +15 -13
- package/src/maker/index.ts +19 -16
- package/src/moneymarket/moneymarketCommonService.ts +14 -2
- package/src/morphoBlue/index.ts +23 -20
- package/src/morphoBlue/merkl.ts +9 -6
- package/src/morphoMidnight/index.ts +13 -13
- package/src/portfolio/customDeFiData.ts +385 -0
- package/src/portfolio/index.ts +307 -331
- package/src/portfolio/lendingProtocols.ts +281 -0
- package/src/savings/index.ts +41 -4
- package/src/services/merkl.ts +209 -19
- package/src/services/priceService.ts +33 -30
- package/src/services/viem.ts +16 -0
- package/src/spark/index.ts +11 -8
- package/src/types/aave.ts +104 -1
- package/src/types/aaveV4.ts +50 -0
- package/src/types/common.ts +1 -0
- package/src/types/compound.ts +38 -2
- package/src/types/curveUsd.ts +17 -1
- package/src/types/fluid.ts +14 -0
- package/src/types/index.ts +1 -0
- package/src/types/liquity.ts +13 -1
- package/src/types/liquityV2.ts +26 -1
- package/src/types/llamaLend.ts +19 -1
- package/src/types/merkl.ts +20 -0
- package/src/types/morphoBlue.ts +3 -0
- package/src/types/portfolio.ts +191 -5
- package/src/types/savings/index.ts +12 -1
- package/src/types/spark.ts +25 -1
- package/src/umbrella/index.ts +7 -5
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import Dec from 'decimal.js';
|
|
2
|
+
import { Client } from 'viem';
|
|
3
|
+
import { EthAddress, NetworkNumber } from '../types/common';
|
|
4
|
+
import {
|
|
5
|
+
AaveMarkets,
|
|
6
|
+
AaveV4Spokes,
|
|
7
|
+
CompoundMarkets,
|
|
8
|
+
CrvUsdMarkets,
|
|
9
|
+
LlamaLendMarkets,
|
|
10
|
+
MorphoBlueMarkets,
|
|
11
|
+
MorphoMidnightMarkets,
|
|
12
|
+
SparkMarkets,
|
|
13
|
+
} from '../markets';
|
|
14
|
+
import {
|
|
15
|
+
AaveMarketInfo,
|
|
16
|
+
AaveV4SpokeInfo,
|
|
17
|
+
AaveVersions,
|
|
18
|
+
CompoundMarketData,
|
|
19
|
+
CompoundVersions,
|
|
20
|
+
CrvUSDMarketData,
|
|
21
|
+
LlamaLendMarketData,
|
|
22
|
+
MorphoBlueMarketData,
|
|
23
|
+
MorphoMidnightMarketData,
|
|
24
|
+
PortfolioMarketsData,
|
|
25
|
+
PortfolioPositionsData,
|
|
26
|
+
PortfolioPositionsDataForAddress,
|
|
27
|
+
PortfolioProtocolData,
|
|
28
|
+
SparkMarketData,
|
|
29
|
+
} from '../types';
|
|
30
|
+
import { _getAaveV3AccountData, _getAaveV3MarketData } from '../aaveV3';
|
|
31
|
+
import { _getAaveV4AccountData, _getAaveV4SpokeData } from '../aaveV4';
|
|
32
|
+
import { _getAaveV2AccountData, _getAaveV2MarketsData } from '../aaveV2';
|
|
33
|
+
import { _getCompoundV2AccountData, _getCompoundV2MarketsData } from '../compoundV2';
|
|
34
|
+
import { _getCompoundV3AccountData, _getCompoundV3MarketsData } from '../compoundV3';
|
|
35
|
+
import { _getCurveUsdGlobalData, _getCurveUsdUserData } from '../curveUsd';
|
|
36
|
+
import { _getLlamaLendGlobalData, _getLlamaLendUserData } from '../llamaLend';
|
|
37
|
+
import { _getMorphoBlueAccountData, _getMorphoBluePortfolioMarketData } from '../morphoBlue';
|
|
38
|
+
import { _getMorphoMidnightAccountData, _getMorphoMidnightMarketData } from '../morphoMidnight';
|
|
39
|
+
import { _getSparkAccountData, _getSparkMarketsData } from '../spark';
|
|
40
|
+
import { ZERO_ADDRESS } from '../constants';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The lending protocols the portfolio reads the same way — a market's data, then each address's position on it — one
|
|
44
|
+
* entry each. Adding such a protocol is its types (its key in PortfolioPositionsDataForAddress and in
|
|
45
|
+
* PortfolioMarketsData) and its entry in LENDING_PROTOCOLS; the portfolio reads, errors and options follow. Maker,
|
|
46
|
+
* Liquity, Fluid and Liquity V2 have shapes of their own and are read by their own code in ./index.ts.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/** What a position read gets. */
|
|
50
|
+
export interface PortfolioReadContext {
|
|
51
|
+
client: Client;
|
|
52
|
+
network: NetworkNumber;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** What a market read gets: also the default client, on Ethereum (Compound V3 reads its prices there). */
|
|
56
|
+
export interface PortfolioMarketsReadContext extends PortfolioReadContext {
|
|
57
|
+
defaultClient: Client;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
type PositionKey = keyof PortfolioPositionsDataForAddress;
|
|
61
|
+
type MarketsKey = keyof PortfolioMarketsData;
|
|
62
|
+
type PositionsOf<K extends PositionKey> = NonNullable<PortfolioPositionsDataForAddress[K]>;
|
|
63
|
+
|
|
64
|
+
/** The data of one of a protocol's positions: what positions[address][K][market] holds as `{ error, data }`. */
|
|
65
|
+
export type LendingPositionData<K extends PositionKey> =
|
|
66
|
+
NonNullable<PositionsOf<K>[keyof PositionsOf<K>]> extends PortfolioProtocolData<infer D> ? D : never;
|
|
67
|
+
|
|
68
|
+
export interface LendingProtocol<K extends PositionKey, M extends MarketsKey, Market extends { value: string }> {
|
|
69
|
+
/** Its key in PortfolioMarketsData. */
|
|
70
|
+
marketsKey: M;
|
|
71
|
+
/** Its name in error messages. */
|
|
72
|
+
label: string;
|
|
73
|
+
/** Its markets on a network; none where it is not deployed. */
|
|
74
|
+
markets: (network: NetworkNumber) => Market[];
|
|
75
|
+
readMarket: (context: PortfolioMarketsReadContext, market: Market) => Promise<PortfolioMarketsData[M][string]>;
|
|
76
|
+
/** An address's position on a market; undefined when the market can hold none. */
|
|
77
|
+
readPosition: (
|
|
78
|
+
context: PortfolioReadContext,
|
|
79
|
+
address: EthAddress,
|
|
80
|
+
market: Market,
|
|
81
|
+
marketData: PortfolioMarketsData[M][string],
|
|
82
|
+
) => Promise<LendingPositionData<K> | undefined>;
|
|
83
|
+
/** Whether there is a position to list: an address without one gets no entry for that market. */
|
|
84
|
+
holds: (position: LendingPositionData<K>) => boolean;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A market's data, or a throw that the caller's catch turns into the position's error entry: read against a missing
|
|
89
|
+
* market, a position would otherwise come back empty and read as "no position".
|
|
90
|
+
*/
|
|
91
|
+
export const requireMarket = <T>(marketsData: Record<string, T>, market: string): T => {
|
|
92
|
+
const marketData = marketsData[market];
|
|
93
|
+
if (!marketData) throw new Error(`Market data for ${market} is not available`);
|
|
94
|
+
return marketData;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** requireMarket for one protocol's key, typed by that key's market data. */
|
|
98
|
+
const requireMarketOf = <M extends MarketsKey>(marketsData: PortfolioMarketsData, key: M, market: string): PortfolioMarketsData[M][string] => {
|
|
99
|
+
// TypeScript reads marketsData[key][market] as any protocol's market data; the key's own is what is stored there.
|
|
100
|
+
const marketData = (marketsData[key] as Record<string, PortfolioMarketsData[M][string] | undefined>)[market];
|
|
101
|
+
if (!marketData) throw new Error(`Market data for ${market} is not available`);
|
|
102
|
+
return marketData;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/** A protocol's entry with its reads, typed by its own market and position types. */
|
|
106
|
+
const lendingProtocol = <K extends PositionKey, M extends MarketsKey, Market extends { value: string }>(
|
|
107
|
+
key: K,
|
|
108
|
+
protocol: LendingProtocol<K, M, Market>,
|
|
109
|
+
) => {
|
|
110
|
+
/** Every market of the protocol into `markets`; resolves to the ones that failed (left out), with their errors. */
|
|
111
|
+
const readMarkets = async (context: PortfolioMarketsReadContext, markets: PortfolioMarketsData): Promise<Record<string, string>> => {
|
|
112
|
+
const protocolMarkets = markets[protocol.marketsKey];
|
|
113
|
+
const failed: Record<string, string> = {};
|
|
114
|
+
await Promise.all(protocol.markets(context.network).map(async (market) => {
|
|
115
|
+
try {
|
|
116
|
+
protocolMarkets[market.value] = await protocol.readMarket(context, market);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
console.error(`Error fetching ${protocol.marketsKey} for market ${market.value}:`, error);
|
|
119
|
+
failed[market.value] = `Error fetching ${protocol.marketsKey} for market ${market.value}`;
|
|
120
|
+
}
|
|
121
|
+
}));
|
|
122
|
+
return failed;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Every address's position on every market into `positions`, each read once its market is in: an entry with the data
|
|
127
|
+
* where the address holds a position, an entry with an error where the read or its market failed, none otherwise.
|
|
128
|
+
*/
|
|
129
|
+
const readPositions = (
|
|
130
|
+
context: PortfolioReadContext,
|
|
131
|
+
addresses: EthAddress[],
|
|
132
|
+
marketsData: Promise<PortfolioMarketsData>,
|
|
133
|
+
positions: PortfolioPositionsData,
|
|
134
|
+
): Promise<void>[] => protocol.markets(context.network).flatMap((market) => addresses.map(async (address) => {
|
|
135
|
+
// Keyed by the protocol's market type in PortfolioPositionsDataForAddress; written here by market.value.
|
|
136
|
+
const byMarket = positions[address.toLowerCase() as EthAddress][key] as Record<string, PortfolioProtocolData<LendingPositionData<K>>>;
|
|
137
|
+
try {
|
|
138
|
+
const marketData = requireMarketOf(await marketsData, protocol.marketsKey, market.value);
|
|
139
|
+
const position = await protocol.readPosition(context, address, market, marketData);
|
|
140
|
+
if (position && protocol.holds(position)) byMarket[market.value] = { error: '', data: position };
|
|
141
|
+
} catch (error) {
|
|
142
|
+
console.error(`Error fetching ${protocol.label} account data for address ${address} on market ${market.value}:`, error);
|
|
143
|
+
byMarket[market.value] = { error: `Error fetching ${protocol.label} account data for address ${address} on market ${market.value}`, data: null };
|
|
144
|
+
}
|
|
145
|
+
}));
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
key, marketsKey: protocol.marketsKey, markets: protocol.markets, readMarkets, readPositions,
|
|
149
|
+
};
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const onNetwork = <Market extends { chainIds: NetworkNumber[] }>(network: NetworkNumber, markets: Market[]) => markets.filter((market) => market.chainIds.includes(network));
|
|
153
|
+
|
|
154
|
+
const suppliesAnything = (position: { suppliedUsd: string }) => new Dec(position.suppliedUsd).gt(0);
|
|
155
|
+
const suppliesOrBorrowsAnything = (position: { suppliedUsd: string, borrowedUsd: string }) => new Dec(position.suppliedUsd).gt(0) || new Dec(position.borrowedUsd).gt(0);
|
|
156
|
+
|
|
157
|
+
export const aaveV3Lending = lendingProtocol('aaveV3', {
|
|
158
|
+
marketsKey: 'aaveV3MarketsData',
|
|
159
|
+
label: 'AaveV3',
|
|
160
|
+
markets: (network): AaveMarketInfo[] => onNetwork(network, [AaveVersions.AaveV3, AaveVersions.AaveV3Lido, AaveVersions.AaveV3Etherfi].map((version) => AaveMarkets(network)[version])),
|
|
161
|
+
readMarket: ({ client, network }, market) => _getAaveV3MarketData(client, network, market),
|
|
162
|
+
readPosition: ({ client, network }, address, market, marketData) => _getAaveV3AccountData(client, network, address, { selectedMarket: market, ...marketData }),
|
|
163
|
+
holds: suppliesAnything,
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
export const aaveV4Lending = lendingProtocol('aaveV4', {
|
|
167
|
+
marketsKey: 'aaveV4SpokesData',
|
|
168
|
+
label: 'AaveV4',
|
|
169
|
+
markets: (network): AaveV4SpokeInfo[] => onNetwork(network, Object.values(AaveV4Spokes(network))),
|
|
170
|
+
readMarket: ({ client, network }, spoke) => _getAaveV4SpokeData(client, network, spoke),
|
|
171
|
+
readPosition: ({ client, network }, address, _spoke, spokeData) => _getAaveV4AccountData(client, network, spokeData, address),
|
|
172
|
+
holds: suppliesAnything,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
export const morphoBlueLending = lendingProtocol('morphoBlue', {
|
|
176
|
+
marketsKey: 'morphoMarketsData',
|
|
177
|
+
label: 'MorphoBlue',
|
|
178
|
+
markets: (network): MorphoBlueMarketData[] => onNetwork(network, Object.values(MorphoBlueMarkets(network))),
|
|
179
|
+
readMarket: ({ client, network }, market) => _getMorphoBluePortfolioMarketData(client, network, market),
|
|
180
|
+
readPosition: ({ client, network }, address, market, marketData) => _getMorphoBlueAccountData(client, network, address, market, marketData),
|
|
181
|
+
holds: suppliesAnything,
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
export const morphoMidnightLending = lendingProtocol('morphoMidnight', {
|
|
185
|
+
marketsKey: 'morphoMidnightMarketsData',
|
|
186
|
+
label: 'MorphoMidnight',
|
|
187
|
+
markets: (network): MorphoMidnightMarketData[] => onNetwork(network, Object.values(MorphoMidnightMarkets(network))),
|
|
188
|
+
readMarket: ({ client, network }, market) => _getMorphoMidnightMarketData(client, network, market),
|
|
189
|
+
// Markets are created lazily on the first position, so an uncreated one can hold no position.
|
|
190
|
+
readPosition: async ({ client, network }, address, market, marketData) => (marketData.isCreated
|
|
191
|
+
? _getMorphoMidnightAccountData(client, network, address, market, marketData)
|
|
192
|
+
: undefined),
|
|
193
|
+
holds: suppliesAnything,
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
export const compoundV3Lending = lendingProtocol('compoundV3', {
|
|
197
|
+
marketsKey: 'compoundV3MarketsData',
|
|
198
|
+
label: 'CompoundV3',
|
|
199
|
+
markets: (network): CompoundMarketData[] => onNetwork(network, Object.values(CompoundMarkets(network)).filter((market) => market.value !== CompoundVersions.CompoundV2)),
|
|
200
|
+
readMarket: ({ client, defaultClient, network }, market) => _getCompoundV3MarketsData(client, network, market, defaultClient),
|
|
201
|
+
readPosition: ({ client, network }, address, market, marketData) => _getCompoundV3AccountData(client, network, address, ZERO_ADDRESS, { selectedMarket: market, assetsData: marketData.assetsData }),
|
|
202
|
+
holds: suppliesAnything,
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
export const sparkLending = lendingProtocol('spark', {
|
|
206
|
+
marketsKey: 'sparkMarketsData',
|
|
207
|
+
label: 'Spark',
|
|
208
|
+
markets: (network): SparkMarketData[] => onNetwork(network, Object.values(SparkMarkets(network))),
|
|
209
|
+
readMarket: ({ client, network }, market) => _getSparkMarketsData(client, network, market),
|
|
210
|
+
readPosition: ({ client, network }, address, market, marketData) => _getSparkAccountData(client, network, address, {
|
|
211
|
+
selectedMarket: market, assetsData: marketData.assetsData, eModeCategoriesData: marketData.eModeCategoriesData,
|
|
212
|
+
}),
|
|
213
|
+
holds: suppliesAnything,
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
export const aaveV2Lending = lendingProtocol('aaveV2', {
|
|
217
|
+
marketsKey: 'aaveV2MarketsData',
|
|
218
|
+
label: 'AaveV2',
|
|
219
|
+
markets: (network): AaveMarketInfo[] => onNetwork(network, [AaveMarkets(network)[AaveVersions.AaveV2]]),
|
|
220
|
+
readMarket: ({ client, network }, market) => _getAaveV2MarketsData(client, network, market),
|
|
221
|
+
readPosition: ({ client, network }, address, market, marketData) => _getAaveV2AccountData(client, network, address, marketData.assetsData, market),
|
|
222
|
+
holds: suppliesAnything,
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
export const compoundV2Lending = lendingProtocol('compoundV2', {
|
|
226
|
+
marketsKey: 'compoundV2MarketsData',
|
|
227
|
+
label: 'CompoundV2',
|
|
228
|
+
markets: (network): CompoundMarketData[] => onNetwork(network, [CompoundMarkets(network)[CompoundVersions.CompoundV2]]),
|
|
229
|
+
readMarket: ({ client, network }) => _getCompoundV2MarketsData(client, network),
|
|
230
|
+
readPosition: ({ client, network }, address, _market, marketData) => _getCompoundV2AccountData(client, network, address, marketData.assetsData),
|
|
231
|
+
holds: suppliesAnything,
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
export const crvUsdLending = lendingProtocol('crvUsd', {
|
|
235
|
+
marketsKey: 'crvUsdMarketsData',
|
|
236
|
+
label: 'Curve USD',
|
|
237
|
+
markets: (network): CrvUSDMarketData[] => onNetwork(network, Object.values(CrvUsdMarkets(network))),
|
|
238
|
+
readMarket: ({ client, network }, market) => _getCurveUsdGlobalData(client, network, market),
|
|
239
|
+
// The market's borrow rate is passed in, so the read does not fetch it again.
|
|
240
|
+
readPosition: ({ client, network }, address, market, marketData) => _getCurveUsdUserData(client, network, address, market, marketData.activeBand, marketData.borrowRate),
|
|
241
|
+
holds: suppliesOrBorrowsAnything,
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
export const llamaLendLending = lendingProtocol('llamaLend', {
|
|
245
|
+
marketsKey: 'llamaLendMarketsData',
|
|
246
|
+
label: 'LlamaLend',
|
|
247
|
+
markets: (network): LlamaLendMarketData[] => ([NetworkNumber.Eth, NetworkNumber.Arb].includes(network) ? onNetwork(network, Object.values(LlamaLendMarkets(network))) : []),
|
|
248
|
+
readMarket: ({ client, network }, market) => _getLlamaLendGlobalData(client, network, market),
|
|
249
|
+
readPosition: async ({ client, network }, address, market, marketData) => ({
|
|
250
|
+
...await _getLlamaLendUserData(client, network, address, market, marketData),
|
|
251
|
+
borrowRate: marketData.borrowRate,
|
|
252
|
+
}),
|
|
253
|
+
holds: suppliesOrBorrowsAnything,
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
/** Every lending protocol read through its entry, in the order positions list them. */
|
|
257
|
+
export const LENDING_PROTOCOLS = [
|
|
258
|
+
aaveV3Lending,
|
|
259
|
+
aaveV4Lending,
|
|
260
|
+
morphoBlueLending,
|
|
261
|
+
morphoMidnightLending,
|
|
262
|
+
compoundV3Lending,
|
|
263
|
+
sparkLending,
|
|
264
|
+
aaveV2Lending,
|
|
265
|
+
compoundV2Lending,
|
|
266
|
+
crvUsdLending,
|
|
267
|
+
llamaLendLending,
|
|
268
|
+
] as const;
|
|
269
|
+
|
|
270
|
+
export type LendingKey = typeof LENDING_PROTOCOLS[number]['key'];
|
|
271
|
+
|
|
272
|
+
/** The keys ./index.ts reads with code of its own. */
|
|
273
|
+
export type SpecialPositionKey = 'maker' | 'liquity' | 'fluid' | 'liquityV2';
|
|
274
|
+
type SpecialMarketsKey = 'liquityV2MarketsData';
|
|
275
|
+
|
|
276
|
+
// Every position key and every markets key is read by an entry here or by its own code in ./index.ts: one added to
|
|
277
|
+
// PortfolioPositionsDataForAddress or PortfolioMarketsData with neither is a compile error on these lines, naming it.
|
|
278
|
+
type UnreadPositionKey = Exclude<PositionKey, LendingKey | SpecialPositionKey>;
|
|
279
|
+
type UnreadMarketsKey = Exclude<MarketsKey, typeof LENDING_PROTOCOLS[number]['marketsKey'] | SpecialMarketsKey>;
|
|
280
|
+
export const EVERY_POSITION_KEY_IS_READ: [UnreadPositionKey] extends [never] ? true : UnreadPositionKey = true;
|
|
281
|
+
export const EVERY_MARKETS_KEY_IS_READ: [UnreadMarketsKey] extends [never] ? true : UnreadMarketsKey = true;
|
package/src/savings/index.ts
CHANGED
|
@@ -2,6 +2,9 @@ import {
|
|
|
2
2
|
MakerDsrType,
|
|
3
3
|
MorphoVaultType,
|
|
4
4
|
SavingsData,
|
|
5
|
+
SavingsDataWithErrors,
|
|
6
|
+
SavingsErrors,
|
|
7
|
+
SavingsVaultKey,
|
|
5
8
|
SkySavingsType,
|
|
6
9
|
SparkSavingsVaultType,
|
|
7
10
|
SummerVaultType,
|
|
@@ -27,11 +30,16 @@ export {
|
|
|
27
30
|
yearnV3Vaults,
|
|
28
31
|
};
|
|
29
32
|
|
|
30
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Every savings vault of a network for the given accounts, and, for each vault that came back without data, why — so
|
|
35
|
+
* a vault that failed is never mistaken for one the accounts have nothing in.
|
|
36
|
+
*/
|
|
37
|
+
export const getSavingsDataWithErrors = async (
|
|
31
38
|
provider: EthereumProvider,
|
|
32
39
|
network: NetworkNumber,
|
|
33
40
|
accounts: EthAddress[],
|
|
34
|
-
) => {
|
|
41
|
+
): Promise<SavingsDataWithErrors> => {
|
|
42
|
+
const isMainnet = network === NetworkNumber.Eth;
|
|
35
43
|
const morphoVaultsList = (Object.keys(morphoVaults.morphoVaultsOptions.MORPHO_VAULTS) as MorphoVaultType[])
|
|
36
44
|
.filter((key) => morphoVaults.morphoVaultsOptions.getMorphoVault(key).network === network);
|
|
37
45
|
const yearnVaultsList = Object.keys(yearnVaults.yearnVaultsOptions.YEARN_VAULTS) as YearnVaultType[];
|
|
@@ -40,7 +48,17 @@ export const getSavingsData = async (
|
|
|
40
48
|
const summerVaultsList = (Object.keys(summerVaults.summerVaultsOptions.SUMMER_VAULTS) as SummerVaultType[])
|
|
41
49
|
.filter((key) => summerVaults.summerVaultsOptions.getSummerVault(key).network === network);
|
|
42
50
|
|
|
51
|
+
// Every vault read on this network, so one left without data or an error can still be reported.
|
|
52
|
+
const vaultKeys: SavingsVaultKey[] = [
|
|
53
|
+
...morphoVaultsList,
|
|
54
|
+
...(isMainnet ? [
|
|
55
|
+
...yearnVaultsList, ...sparkSavingsVaultsList, ...yearnV3VaultsList, MakerDsrType.MakerDsrVault, SkySavingsType.SkySavings,
|
|
56
|
+
] : []),
|
|
57
|
+
...summerVaultsList,
|
|
58
|
+
];
|
|
59
|
+
|
|
43
60
|
const savingsData: SavingsData = {};
|
|
61
|
+
const errors: SavingsErrors = {};
|
|
44
62
|
|
|
45
63
|
await Promise.all([
|
|
46
64
|
...(morphoVaultsList.length ? [
|
|
@@ -51,10 +69,11 @@ export const getSavingsData = async (
|
|
|
51
69
|
Object.assign(savingsData, data);
|
|
52
70
|
} catch (err) {
|
|
53
71
|
console.error('[getSavingsData] Error fetching morpho vaults:', err);
|
|
72
|
+
morphoVaultsList.forEach((vaultKey) => { errors[vaultKey] = `Error fetching morpho vault ${vaultKey}`; });
|
|
54
73
|
}
|
|
55
74
|
})(),
|
|
56
75
|
] : []),
|
|
57
|
-
...(
|
|
76
|
+
...(isMainnet ? [
|
|
58
77
|
...yearnVaultsList.map(async (vaultKey) => {
|
|
59
78
|
try {
|
|
60
79
|
const vault = yearnVaults.yearnVaultsOptions.getYearnVault(vaultKey);
|
|
@@ -62,6 +81,7 @@ export const getSavingsData = async (
|
|
|
62
81
|
savingsData[vaultKey] = data;
|
|
63
82
|
} catch (err) {
|
|
64
83
|
console.error(`[getSavingsData] Error fetching yearn vault ${vaultKey}:`, err);
|
|
84
|
+
errors[vaultKey] = `Error fetching yearn vault ${vaultKey}`;
|
|
65
85
|
}
|
|
66
86
|
}),
|
|
67
87
|
...sparkSavingsVaultsList.map(async (vaultKey) => {
|
|
@@ -71,6 +91,7 @@ export const getSavingsData = async (
|
|
|
71
91
|
savingsData[vaultKey] = data;
|
|
72
92
|
} catch (err) {
|
|
73
93
|
console.error(`[getSavingsData] Error fetching spark savings vault ${vaultKey}:`, err);
|
|
94
|
+
errors[vaultKey] = `Error fetching spark savings vault ${vaultKey}`;
|
|
74
95
|
}
|
|
75
96
|
}),
|
|
76
97
|
...yearnV3VaultsList.map(async (vaultKey) => {
|
|
@@ -80,6 +101,7 @@ export const getSavingsData = async (
|
|
|
80
101
|
savingsData[vaultKey] = data;
|
|
81
102
|
} catch (err) {
|
|
82
103
|
console.error(`[getSavingsData] Error fetching yearn v3 vault ${vaultKey}:`, err);
|
|
104
|
+
errors[vaultKey] = `Error fetching yearn v3 vault ${vaultKey}`;
|
|
83
105
|
}
|
|
84
106
|
}),
|
|
85
107
|
(async () => {
|
|
@@ -88,6 +110,7 @@ export const getSavingsData = async (
|
|
|
88
110
|
savingsData[MakerDsrType.MakerDsrVault] = data;
|
|
89
111
|
} catch (err) {
|
|
90
112
|
console.error('[getSavingsData] Error fetching maker DSR data:', err);
|
|
113
|
+
errors[MakerDsrType.MakerDsrVault] = 'Error fetching maker DSR data';
|
|
91
114
|
}
|
|
92
115
|
})(),
|
|
93
116
|
(async () => {
|
|
@@ -96,6 +119,7 @@ export const getSavingsData = async (
|
|
|
96
119
|
savingsData[SkySavingsType.SkySavings] = data;
|
|
97
120
|
} catch (err) {
|
|
98
121
|
console.error('[getSavingsData] Error fetching Sky savings data:', err);
|
|
122
|
+
errors[SkySavingsType.SkySavings] = 'Error fetching Sky savings data';
|
|
99
123
|
}
|
|
100
124
|
})(),
|
|
101
125
|
] : []),
|
|
@@ -106,9 +130,22 @@ export const getSavingsData = async (
|
|
|
106
130
|
savingsData[vaultKey] = data;
|
|
107
131
|
} catch (err) {
|
|
108
132
|
console.error(`[getSavingsData] Error fetching summer vault ${vaultKey}:`, err);
|
|
133
|
+
errors[vaultKey] = `Error fetching summer vault ${vaultKey}`;
|
|
109
134
|
}
|
|
110
135
|
}),
|
|
111
136
|
]);
|
|
112
137
|
|
|
113
|
-
return
|
|
138
|
+
// getMorphoVaultsData leaves out, without throwing, a vault whose on-chain reads failed or that the Morpho API did not return.
|
|
139
|
+
vaultKeys.forEach((vaultKey) => {
|
|
140
|
+
if (!savingsData[vaultKey] && !errors[vaultKey]) errors[vaultKey] = `No data returned for savings vault ${vaultKey}`;
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
return { data: savingsData, errors };
|
|
114
144
|
};
|
|
145
|
+
|
|
146
|
+
/** Every savings vault of a network for the given accounts. A vault that failed is left out: use getSavingsDataWithErrors to tell why. */
|
|
147
|
+
export const getSavingsData = async (
|
|
148
|
+
provider: EthereumProvider,
|
|
149
|
+
network: NetworkNumber,
|
|
150
|
+
accounts: EthAddress[],
|
|
151
|
+
): Promise<SavingsData> => (await getSavingsDataWithErrors(provider, network, accounts)).data;
|
package/src/services/merkl.ts
CHANGED
|
@@ -1,31 +1,221 @@
|
|
|
1
|
-
import
|
|
1
|
+
import memoize from 'memoizee';
|
|
2
|
+
import {
|
|
3
|
+
MerklAprRecord, MerklCampaignListItem, MerklOpportunity, OpportunityStatus,
|
|
4
|
+
} from '../types';
|
|
2
5
|
import { LONGER_TIMEOUT } from './utils';
|
|
3
6
|
|
|
4
|
-
const
|
|
7
|
+
const MERKL_API_URL = 'https://fe.defisaver.com/api/merkl';
|
|
8
|
+
const MERKL_OPPORTUNITIES_URL = `${MERKL_API_URL}/opportunities`;
|
|
9
|
+
const MERKL_CAMPAIGNS_URL = `${MERKL_API_URL}/campaigns`;
|
|
10
|
+
|
|
11
|
+
// Merkl caps list pages at 100 items; opportunity ids are batched below that so a single page
|
|
12
|
+
// covers every id in the batch.
|
|
13
|
+
const MERKL_MAX_PAGE_ITEMS = 100;
|
|
14
|
+
const OPPORTUNITY_ID_BATCH_SIZE = 50;
|
|
15
|
+
// APR history is fetched per opportunity, so historical lookups are throttled to keep a block with
|
|
16
|
+
// many live campaigns from firing every request at once.
|
|
17
|
+
const APR_RECORDS_CONCURRENCY = 10;
|
|
18
|
+
const SECONDS_PER_HOUR = 60 * 60;
|
|
19
|
+
const SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;
|
|
20
|
+
// Historical lookups describe the past, so their responses are reused for a while: a job that
|
|
21
|
+
// walks many blocks (or fetches several protocols/chains at one block in parallel) would otherwise
|
|
22
|
+
// re-request the same campaign lists, opportunities and APR buckets for every block.
|
|
23
|
+
const HISTORY_CACHE_TTL = 5 * 60 * 1000;
|
|
24
|
+
|
|
25
|
+
const merklGet = async <T>(url: string, query: Record<string, string>, label: string): Promise<T> => {
|
|
26
|
+
const res = await fetch(`${url}?${new URLSearchParams(query)}`, { signal: AbortSignal.timeout(LONGER_TIMEOUT) });
|
|
27
|
+
if (!res.ok) {
|
|
28
|
+
const body = await res.text().catch(() => '');
|
|
29
|
+
throw new Error(`Failed to fetch Merkl ${label} (HTTP ${res.status}${body ? `: ${body.slice(0, 200)}` : ''})`);
|
|
30
|
+
}
|
|
31
|
+
return res.json();
|
|
32
|
+
};
|
|
5
33
|
|
|
6
34
|
/**
|
|
7
|
-
* Fetches every page matching the query
|
|
8
|
-
* `items`
|
|
35
|
+
* Fetches every page matching the query, advancing `page` until an empty page comes back. When
|
|
36
|
+
* `items` is omitted, Merkl's default page size applies and no client-side maximum is imposed.
|
|
9
37
|
*/
|
|
10
|
-
|
|
11
|
-
const
|
|
38
|
+
const fetchAllMerklPages = async <T>(url: string, query: Record<string, string>, label: string, items?: number): Promise<T[]> => {
|
|
39
|
+
const results: T[] = [];
|
|
12
40
|
let page = 0;
|
|
13
|
-
let
|
|
41
|
+
let pageResults: T[];
|
|
14
42
|
|
|
15
43
|
do {
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
});
|
|
20
|
-
if (!res.ok) throw new Error(`Failed to fetch Merkl opportunities page ${page}`);
|
|
21
|
-
|
|
22
|
-
const data = await res.json(); // eslint-disable-line no-await-in-loop
|
|
23
|
-
if (!Array.isArray(data)) throw new Error(`Invalid Merkl opportunities response on page ${page}`);
|
|
44
|
+
const pageQuery = { ...query, page: page.toString(), ...(items ? { items: items.toString() } : {}) };
|
|
45
|
+
const data = await merklGet<unknown>(url, pageQuery, `${label} page ${page}`); // eslint-disable-line no-await-in-loop
|
|
46
|
+
if (!Array.isArray(data)) throw new Error(`Invalid Merkl ${label} response on page ${page}`);
|
|
24
47
|
|
|
25
|
-
|
|
26
|
-
|
|
48
|
+
pageResults = data as T[];
|
|
49
|
+
results.push(...pageResults);
|
|
27
50
|
page += 1;
|
|
28
|
-
} while (
|
|
51
|
+
} while (pageResults.length > 0);
|
|
52
|
+
|
|
53
|
+
return results;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Fetches every opportunity matching the query. Merkl returns 20 opportunities by default, so omitting
|
|
58
|
+
* `items` and advancing `page` avoids imposing a client-side maximum on the result set.
|
|
59
|
+
*/
|
|
60
|
+
export const fetchAllMerklOpportunities = async (query: Record<string, string>): Promise<MerklOpportunity[]> => (
|
|
61
|
+
fetchAllMerklPages<MerklOpportunity>(MERKL_OPPORTUNITIES_URL, query, 'opportunities')
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
/** Fetches every campaign matching the query, e.g. `{ mainProtocolId: 'aave', status: 'LIVE,PAST' }`. */
|
|
65
|
+
export const fetchAllMerklCampaigns = async (query: Record<string, string>): Promise<MerklCampaignListItem[]> => (
|
|
66
|
+
fetchAllMerklPages<MerklCampaignListItem>(MERKL_CAMPAIGNS_URL, query, 'campaigns', MERKL_MAX_PAGE_ITEMS)
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
const fetchAllMerklCampaignsCached = memoize(fetchAllMerklCampaigns, {
|
|
70
|
+
promise: true,
|
|
71
|
+
maxAge: HISTORY_CACHE_TTL,
|
|
72
|
+
normalizer: ([query]: [Record<string, string>]) => JSON.stringify(Object.entries(query).sort()),
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Fetches the opportunities with the given Merkl-internal ids, regardless of their current status.
|
|
77
|
+
* Ids Merkl no longer serves (hidden or test campaigns) are simply absent from the result.
|
|
78
|
+
*/
|
|
79
|
+
export const fetchMerklOpportunitiesByIds = async (ids: string[]): Promise<MerklOpportunity[]> => {
|
|
80
|
+
const batches: string[][] = [];
|
|
81
|
+
for (let i = 0; i < ids.length; i += OPPORTUNITY_ID_BATCH_SIZE) batches.push(ids.slice(i, i + OPPORTUNITY_ID_BATCH_SIZE));
|
|
82
|
+
const results = await Promise.all(batches.map((batch) => merklGet<unknown>(
|
|
83
|
+
MERKL_OPPORTUNITIES_URL,
|
|
84
|
+
{ id: batch.join(','), items: MERKL_MAX_PAGE_ITEMS.toString() },
|
|
85
|
+
'opportunities by id',
|
|
86
|
+
)));
|
|
87
|
+
return results.flatMap((data) => {
|
|
88
|
+
if (!Array.isArray(data)) throw new Error('Invalid Merkl opportunities by id response');
|
|
89
|
+
return data as MerklOpportunity[];
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const fetchMerklOpportunitiesByIdsCached = memoize(fetchMerklOpportunitiesByIds, {
|
|
94
|
+
promise: true,
|
|
95
|
+
maxAge: HISTORY_CACHE_TTL,
|
|
96
|
+
normalizer: ([ids]: [string[]]) => [...ids].sort().join(','),
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const fetchLatestMerklAprRecord = async (opportunityId: string, grain: 'HOUR' | 'DAY', to: number): Promise<MerklAprRecord | undefined> => {
|
|
100
|
+
const records = await merklGet<unknown>(`${MERKL_OPPORTUNITIES_URL}/${opportunityId}/apr-records`, {
|
|
101
|
+
grain,
|
|
102
|
+
from: (to - SECONDS_PER_DAY).toString(),
|
|
103
|
+
to: to.toString(),
|
|
104
|
+
items: '1',
|
|
105
|
+
}, `APR records for opportunity ${opportunityId}`);
|
|
106
|
+
if (!Array.isArray(records)) throw new Error(`Invalid Merkl APR records response for opportunity ${opportunityId}`);
|
|
107
|
+
return (records as MerklAprRecord[])[0];
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Returns the reward APR Merkl recorded for the opportunity at the given unix timestamp (seconds),
|
|
112
|
+
* or `undefined` when no campaign was computing for it then. Records are buckets keyed by their
|
|
113
|
+
* start, newest first, and each carries the last value recorded in the bucket. The hourly bucket of
|
|
114
|
+
* the timestamp's hour is used when Merkl still has it — it keeps hourly history for roughly the
|
|
115
|
+
* last ten weeks — and the daily bucket of the timestamp's day otherwise. Either window is a day
|
|
116
|
+
* wide to tolerate computation gaps and aligned to the bucket, so every block within one hour asks
|
|
117
|
+
* for (and caches) the same records.
|
|
118
|
+
*/
|
|
119
|
+
export const fetchMerklOpportunityAprAt = async (opportunityId: string, timestamp: number): Promise<number | undefined> => {
|
|
120
|
+
const hour = Math.floor(timestamp / SECONDS_PER_HOUR) * SECONDS_PER_HOUR;
|
|
121
|
+
const hourly = await fetchLatestMerklAprRecord(opportunityId, 'HOUR', hour);
|
|
122
|
+
if (hourly) return hourly.apr;
|
|
123
|
+
const day = Math.floor(timestamp / SECONDS_PER_DAY) * SECONDS_PER_DAY;
|
|
124
|
+
return (await fetchLatestMerklAprRecord(opportunityId, 'DAY', day))?.apr;
|
|
125
|
+
};
|
|
29
126
|
|
|
30
|
-
|
|
127
|
+
const fetchMerklOpportunityAprAtCached = memoize(fetchMerklOpportunityAprAt, {
|
|
128
|
+
promise: true,
|
|
129
|
+
maxAge: HISTORY_CACHE_TTL,
|
|
130
|
+
normalizer: ([opportunityId, timestamp]: [string, number]) => `${opportunityId}:${Math.floor(timestamp / SECONDS_PER_HOUR)}`,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
/** Drops every cached historical response (campaign lists, opportunities, APR buckets). */
|
|
134
|
+
export const clearMerklHistoryCache = () => {
|
|
135
|
+
fetchAllMerklCampaignsCached.clear();
|
|
136
|
+
fetchMerklOpportunitiesByIdsCached.clear();
|
|
137
|
+
fetchMerklOpportunityAprAtCached.clear();
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const mapWithConcurrency = async <T, R>(items: T[], concurrency: number, fn: (item: T) => Promise<R>): Promise<R[]> => {
|
|
141
|
+
const results: R[] = [];
|
|
142
|
+
for (let i = 0; i < items.length; i += concurrency) {
|
|
143
|
+
results.push(...await Promise.all(items.slice(i, i + concurrency).map(fn))); // eslint-disable-line no-await-in-loop
|
|
144
|
+
}
|
|
145
|
+
return results;
|
|
31
146
|
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Reconstructs the opportunities that were live at `timestamp` (unix seconds), shaped like the
|
|
150
|
+
* live listing so the per-protocol reward mappers can consume either without knowing which they got:
|
|
151
|
+
* 1. every LIVE or PAST campaign for the protocol (and chain, when the query names one) is listed
|
|
152
|
+
* once per cache period — the list is block-independent, the exact window check happens here —
|
|
153
|
+
* and the ones whose [start, end] covers the timestamp identify the opportunities rewarded
|
|
154
|
+
* then (the live listing can't: campaigns live then are mostly PAST now and ones live now
|
|
155
|
+
* didn't exist then);
|
|
156
|
+
* 2. those opportunities are loaded by id (works for PAST ones too) and narrowed to `query.type`
|
|
157
|
+
* and `isRelevant`, so no APR history is fetched for opportunities the caller would discard;
|
|
158
|
+
* 3. each one's `apr` is replaced with the value Merkl recorded at the timestamp, and ones with no
|
|
159
|
+
* record then are dropped, since nothing was being computed for them.
|
|
160
|
+
* `status` is forced to LIVE so status filters downstream keep working, `campaigns` carries the
|
|
161
|
+
* covering campaigns, and a reward token breakdown is synthesized from the campaign's reward token
|
|
162
|
+
* when Merkl no longer serves one for the opportunity (it drops them once an opportunity is PAST).
|
|
163
|
+
* `query.status` is ignored: it describes the present, not the requested moment.
|
|
164
|
+
*/
|
|
165
|
+
export const fetchMerklOpportunitiesAt = async (
|
|
166
|
+
query: Record<string, string>,
|
|
167
|
+
timestamp: number,
|
|
168
|
+
isRelevant: (opportunity: MerklOpportunity) => boolean = () => true,
|
|
169
|
+
): Promise<MerklOpportunity[]> => {
|
|
170
|
+
const campaignQuery: Record<string, string> = { status: 'LIVE,PAST' };
|
|
171
|
+
if (query.mainProtocolId) campaignQuery.mainProtocolId = query.mainProtocolId;
|
|
172
|
+
if (query.chainId) campaignQuery.chainId = query.chainId;
|
|
173
|
+
|
|
174
|
+
const campaigns = (await fetchAllMerklCampaignsCached(campaignQuery))
|
|
175
|
+
.filter((c) => c.opportunityId && +(c.startTimestamp ?? 0) <= timestamp && timestamp <= +(c.endTimestamp ?? 0));
|
|
176
|
+
const campaignsByOpportunity: Record<string, MerklCampaignListItem[]> = {};
|
|
177
|
+
campaigns.forEach((c) => {
|
|
178
|
+
if (!campaignsByOpportunity[c.opportunityId]) campaignsByOpportunity[c.opportunityId] = [];
|
|
179
|
+
campaignsByOpportunity[c.opportunityId].push(c);
|
|
180
|
+
});
|
|
181
|
+
const opportunityIds = Object.keys(campaignsByOpportunity);
|
|
182
|
+
if (!opportunityIds.length) return [];
|
|
183
|
+
|
|
184
|
+
const types = query.type?.split(',').filter(Boolean);
|
|
185
|
+
const opportunities = (await fetchMerklOpportunitiesByIdsCached(opportunityIds))
|
|
186
|
+
.filter((o) => (!types?.length || types.includes(o.type)) && isRelevant(o));
|
|
187
|
+
|
|
188
|
+
const aprs = await mapWithConcurrency(opportunities, APR_RECORDS_CONCURRENCY, (o) => fetchMerklOpportunityAprAtCached(o.id, timestamp));
|
|
189
|
+
|
|
190
|
+
return opportunities.flatMap((o, i) => {
|
|
191
|
+
const apr = aprs[i];
|
|
192
|
+
if (apr === undefined) return [];
|
|
193
|
+
const coveringCampaigns = campaignsByOpportunity[o.id];
|
|
194
|
+
const rewardToken = coveringCampaigns.find((c) => c.rewardToken)?.rewardToken;
|
|
195
|
+
const hasBreakdown = !!o.rewardsRecord?.breakdowns?.length;
|
|
196
|
+
return [{
|
|
197
|
+
...o,
|
|
198
|
+
status: OpportunityStatus.LIVE,
|
|
199
|
+
apr,
|
|
200
|
+
campaigns: coveringCampaigns,
|
|
201
|
+
rewardsRecord: hasBreakdown || !rewardToken ? o.rewardsRecord : {
|
|
202
|
+
...o.rewardsRecord,
|
|
203
|
+
breakdowns: [{ token: rewardToken, campaignId: coveringCampaigns[0].campaignId } as MerklOpportunity['rewardsRecord']['breakdowns'][number]],
|
|
204
|
+
},
|
|
205
|
+
}];
|
|
206
|
+
});
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Live opportunities when no timestamp is given, otherwise the opportunities as they were at that
|
|
211
|
+
* unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`. `isRelevant` only applies to the
|
|
212
|
+
* historical path, where it saves fetching APR history for opportunities the caller would discard;
|
|
213
|
+
* callers still filter the live listing themselves.
|
|
214
|
+
*/
|
|
215
|
+
export const fetchMerklOpportunities = async (
|
|
216
|
+
query: Record<string, string>,
|
|
217
|
+
asOfTimestamp?: number,
|
|
218
|
+
isRelevant?: (opportunity: MerklOpportunity) => boolean,
|
|
219
|
+
): Promise<MerklOpportunity[]> => (
|
|
220
|
+
asOfTimestamp === undefined ? fetchAllMerklOpportunities(query) : fetchMerklOpportunitiesAt(query, asOfTimestamp, isRelevant)
|
|
221
|
+
);
|