@defisaver/positions-sdk 2.1.175-looping-dev → 2.1.175-pendle-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 +4 -3
- package/cjs/aaveV3/index.js +14 -10
- package/cjs/aaveV3/merkl.d.ts +5 -1
- package/cjs/aaveV3/merkl.js +8 -3
- package/cjs/aaveV4/index.d.ts +4 -3
- package/cjs/aaveV4/index.js +19 -16
- package/cjs/aaveV4/merkl.d.ts +10 -2
- package/cjs/aaveV4/merkl.js +15 -6
- package/cjs/claiming/aaveV3.d.ts +2 -2
- package/cjs/claiming/aaveV3.js +5 -4
- package/cjs/claiming/king.d.ts +2 -2
- package/cjs/claiming/king.js +3 -2
- package/cjs/claiming/spark.d.ts +3 -3
- 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 -22
- 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 +4 -4
- package/cjs/liquity/index.js +23 -23
- package/cjs/liquityV2/index.d.ts +10 -10
- package/cjs/liquityV2/index.js +59 -59
- 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/markets/morphoBlue/index.d.ts +2 -0
- package/cjs/markets/morphoBlue/index.js +19 -2
- package/cjs/moneymarket/moneymarketCommonService.js +14 -3
- 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 +1 -0
- package/cjs/portfolio/index.js +1 -0
- 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/staking/staking.js +3 -1
- package/cjs/types/aaveV4.d.ts +1 -0
- package/cjs/types/common.d.ts +1 -0
- package/cjs/types/common.js +1 -0
- package/cjs/types/merkl.d.ts +18 -0
- package/cjs/types/morphoBlue.d.ts +1 -0
- package/cjs/types/morphoBlue.js +1 -0
- package/cjs/types/portfolio.d.ts +37 -0
- package/cjs/types/portfolio.js +18 -0
- package/cjs/umbrella/index.d.ts +2 -2
- 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 +4 -3
- package/esm/aaveV3/index.js +15 -11
- package/esm/aaveV3/merkl.d.ts +5 -1
- package/esm/aaveV3/merkl.js +9 -4
- package/esm/aaveV4/index.d.ts +4 -3
- package/esm/aaveV4/index.js +20 -17
- package/esm/aaveV4/merkl.d.ts +10 -2
- package/esm/aaveV4/merkl.js +16 -7
- package/esm/claiming/aaveV3.d.ts +2 -2
- package/esm/claiming/aaveV3.js +5 -4
- package/esm/claiming/king.d.ts +2 -2
- package/esm/claiming/king.js +3 -2
- package/esm/claiming/spark.d.ts +3 -3
- package/esm/claiming/spark.js +8 -7
- 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 -22
- 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 +4 -4
- package/esm/liquity/index.js +23 -23
- package/esm/liquityV2/index.d.ts +10 -10
- package/esm/liquityV2/index.js +60 -60
- 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/markets/morphoBlue/index.d.ts +2 -0
- package/esm/markets/morphoBlue/index.js +16 -0
- package/esm/moneymarket/moneymarketCommonService.js +14 -3
- 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 +1 -0
- package/esm/portfolio/index.js +1 -0
- 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/staking/staking.js +3 -1
- package/esm/types/aaveV4.d.ts +1 -0
- package/esm/types/common.d.ts +1 -0
- package/esm/types/common.js +1 -0
- package/esm/types/merkl.d.ts +18 -0
- package/esm/types/morphoBlue.d.ts +1 -0
- package/esm/types/morphoBlue.js +1 -0
- package/esm/types/portfolio.d.ts +37 -0
- package/esm/types/portfolio.js +17 -1
- package/esm/umbrella/index.d.ts +2 -2
- package/esm/umbrella/index.js +5 -4
- package/package.json +2 -2
- package/src/aaveV2/index.ts +7 -7
- package/src/aaveV3/index.ts +15 -11
- package/src/aaveV3/merkl.ts +9 -4
- package/src/aaveV4/index.ts +19 -16
- package/src/aaveV4/merkl.ts +16 -7
- package/src/claiming/aaveV3.ts +5 -3
- package/src/claiming/king.ts +6 -3
- package/src/claiming/spark.ts +9 -6
- 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 +88 -70
- 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 +23 -23
- package/src/liquityV2/index.ts +64 -56
- package/src/llamaLend/index.ts +15 -13
- package/src/maker/index.ts +19 -16
- package/src/markets/morphoBlue/index.ts +16 -0
- package/src/moneymarket/moneymarketCommonService.ts +15 -3
- 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 +1 -0
- 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/staking/staking.ts +2 -1
- package/src/types/aaveV4.ts +1 -0
- package/src/types/common.ts +1 -0
- package/src/types/merkl.ts +20 -0
- package/src/types/morphoBlue.ts +1 -0
- package/src/types/portfolio.ts +40 -0
- package/src/umbrella/index.ts +6 -5
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import Dec from 'decimal.js';
|
|
2
|
+
import {
|
|
3
|
+
Blockish, EthAddress, EthereumProvider, NetworkNumber,
|
|
4
|
+
} from '../types/common';
|
|
5
|
+
import {
|
|
6
|
+
AaveMarkets,
|
|
7
|
+
AaveV4Spokes,
|
|
8
|
+
CompoundMarkets,
|
|
9
|
+
CrvUsdMarkets,
|
|
10
|
+
LiquityV2Markets,
|
|
11
|
+
LlamaLendMarkets,
|
|
12
|
+
MakerActiveIlks,
|
|
13
|
+
MorphoBlueMarkets,
|
|
14
|
+
MorphoMidnightMarkets,
|
|
15
|
+
SparkMarkets,
|
|
16
|
+
} from '../markets';
|
|
17
|
+
import {
|
|
18
|
+
AaveVersions,
|
|
19
|
+
CdpInfo,
|
|
20
|
+
CompoundVersions,
|
|
21
|
+
CustomDeFiData,
|
|
22
|
+
CustomDeFiDataOptions,
|
|
23
|
+
PortfolioPositionsData,
|
|
24
|
+
PortfolioProtocol,
|
|
25
|
+
ShifterPortfolioMarketsData,
|
|
26
|
+
} from '../types';
|
|
27
|
+
import { getBlockTimestamp, getViemProvider } from '../services/viem';
|
|
28
|
+
import { ZERO_ADDRESS } from '../constants';
|
|
29
|
+
import { _getAaveV2AccountData, _getAaveV2MarketsData } from '../aaveV2';
|
|
30
|
+
import { _getAaveV3AccountData, _getAaveV3MarketData, getStakeAaveData } from '../aaveV3';
|
|
31
|
+
import { _getAaveV4AccountData, _getAaveV4SpokeData } from '../aaveV4';
|
|
32
|
+
import { _getCompoundV2AccountData, _getCompoundV2MarketsData } from '../compoundV2';
|
|
33
|
+
import { _getCompoundV3AccountData, _getCompoundV3MarketsData } from '../compoundV3';
|
|
34
|
+
import { _getSparkAccountData, _getSparkMarketsData } from '../spark';
|
|
35
|
+
import { _getCurveUsdGlobalData, _getCurveUsdUserData } from '../curveUsd';
|
|
36
|
+
import { _getLlamaLendGlobalData, _getLlamaLendUserData } from '../llamaLend';
|
|
37
|
+
import { _getMorphoBlueAccountData, _getMorphoBluePortfolioMarketData, getMorphoEarn } from '../morphoBlue';
|
|
38
|
+
import { _getMorphoMidnightAccountData, _getMorphoMidnightMarketData } from '../morphoMidnight';
|
|
39
|
+
import { _getMakerCdpData, _getMakerIlksData, _getUserCdps } from '../maker';
|
|
40
|
+
import { _getLiquityTroveInfo, getLiquityStakingData } from '../liquity';
|
|
41
|
+
import { _getLiquityV2MarketData, getLiquitySAndYBold, getLiquityV2Staking } from '../liquityV2';
|
|
42
|
+
import { _getAllFluidMarketDataPortfolio, _getAllUserEarnPositionsWithFTokens, _getUserPositionsPortfolio } from '../fluid';
|
|
43
|
+
import { getUmbrellaData } from '../umbrella';
|
|
44
|
+
import { getMerklUnclaimedRewards, getUnclaimedRewardsForAllMarkets } from '../claiming/aaveV3';
|
|
45
|
+
import { fetchSparkAirdropRewards, fetchSparkRewards } from '../claiming/spark';
|
|
46
|
+
import { getKingRewards } from '../claiming/king';
|
|
47
|
+
import { fetchEthenaAirdropRewards } from '../claiming/ethena';
|
|
48
|
+
import { getUniswapRewards } from '../claiming/uniswap';
|
|
49
|
+
|
|
50
|
+
const lower = (address: EthAddress) => address.toLowerCase() as EthAddress;
|
|
51
|
+
const positive = (value: string | undefined) => new Dec(value || '0').gt(0);
|
|
52
|
+
|
|
53
|
+
const supported = <T extends { chainIds: NetworkNumber[] }>(list: Record<string, T>, network: NetworkNumber) => (
|
|
54
|
+
Object.values(list).filter((m) => m.chainIds.includes(network))
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
export async function getCustomDeFiData(
|
|
58
|
+
provider: EthereumProvider,
|
|
59
|
+
network: NetworkNumber,
|
|
60
|
+
defaultProvider: EthereumProvider,
|
|
61
|
+
addresses: EthAddress[],
|
|
62
|
+
options: CustomDeFiDataOptions = {},
|
|
63
|
+
): Promise<CustomDeFiData> {
|
|
64
|
+
const {
|
|
65
|
+
protocols = Object.values(PortfolioProtocol),
|
|
66
|
+
fetchStaking = false,
|
|
67
|
+
fetchRewards = false,
|
|
68
|
+
returnEmptyEModePositions = false,
|
|
69
|
+
fetchFluidMarkets = false,
|
|
70
|
+
isSim = false,
|
|
71
|
+
} = options;
|
|
72
|
+
// JSON-RPC body ends up ~4x the calldata cap; 250k keeps it under the ~2.5MB provider limit.
|
|
73
|
+
const batchSize = options.batchSize ?? (isSim ? 2_000 : 250_000);
|
|
74
|
+
const has = (protocol: PortfolioProtocol) => protocols.includes(protocol);
|
|
75
|
+
|
|
76
|
+
const isMainnet = network === NetworkNumber.Eth;
|
|
77
|
+
const isFluidSupported = [NetworkNumber.Eth, NetworkNumber.Arb, NetworkNumber.Base, NetworkNumber.Plasma].includes(network);
|
|
78
|
+
|
|
79
|
+
const client = getViemProvider(provider, network, { batch: { multicall: { batchSize } } });
|
|
80
|
+
const defaultClient = getViemProvider(defaultProvider, network, { batch: { multicall: { batchSize } } });
|
|
81
|
+
// Every fetch below takes the block explicitly and passes it to each of its contract reads.
|
|
82
|
+
// Time-keyed sources (Merkl rewards) need the block's timestamp instead, resolved once here (no
|
|
83
|
+
// RPC call for 'latest') and handed to the market fetches so they don't each look it up.
|
|
84
|
+
const blockNumber: Blockish = options.blockNumber ?? 'latest';
|
|
85
|
+
const blockTimestamp = await getBlockTimestamp(client, blockNumber);
|
|
86
|
+
|
|
87
|
+
const aaveV3Markets = has(PortfolioProtocol.AaveV3)
|
|
88
|
+
? [AaveVersions.AaveV3, AaveVersions.AaveV3Lido, AaveVersions.AaveV3Etherfi].map((v) => AaveMarkets(network)[v]).filter((m) => m.chainIds.includes(network))
|
|
89
|
+
: [];
|
|
90
|
+
const aaveV2Markets = has(PortfolioProtocol.AaveV2) ? [AaveMarkets(network)[AaveVersions.AaveV2]].filter((m) => m.chainIds.includes(network)) : [];
|
|
91
|
+
const aaveV4Spokes = has(PortfolioProtocol.AaveV4) ? supported(AaveV4Spokes(network), network) : [];
|
|
92
|
+
const compoundV3Markets = has(PortfolioProtocol.CompoundV3) ? supported(CompoundMarkets(network), network).filter((m) => m.value !== CompoundVersions.CompoundV2) : [];
|
|
93
|
+
const compoundV2Markets = has(PortfolioProtocol.CompoundV2) ? [CompoundMarkets(network)[CompoundVersions.CompoundV2]].filter((m) => m.chainIds.includes(network)) : [];
|
|
94
|
+
const sparkMarkets = has(PortfolioProtocol.Spark) ? supported(SparkMarkets(network), network) : [];
|
|
95
|
+
const morphoMarkets = has(PortfolioProtocol.MorphoBlue) ? supported(MorphoBlueMarkets(network), network) : [];
|
|
96
|
+
const morphoMidnightMarkets = has(PortfolioProtocol.MorphoMidnight) ? supported(MorphoMidnightMarkets(network), network) : [];
|
|
97
|
+
const crvUsdMarkets = has(PortfolioProtocol.CrvUsd) ? supported(CrvUsdMarkets(network), network) : [];
|
|
98
|
+
const llamaLendMarkets = has(PortfolioProtocol.LlamaLend) && [NetworkNumber.Eth, NetworkNumber.Arb].includes(network) ? supported(LlamaLendMarkets(network), network) : [];
|
|
99
|
+
const liquityV2Markets = has(PortfolioProtocol.LiquityV2) && isMainnet ? Object.values(LiquityV2Markets(network)) : [];
|
|
100
|
+
const liquityV2StakingMarkets = liquityV2Markets.filter((m) => !m.isLegacy);
|
|
101
|
+
const fetchMaker = has(PortfolioProtocol.Maker) && isMainnet;
|
|
102
|
+
const fetchLiquity = has(PortfolioProtocol.Liquity) && isMainnet;
|
|
103
|
+
const fetchFluid = has(PortfolioProtocol.Fluid) && isFluidSupported;
|
|
104
|
+
|
|
105
|
+
const markets: ShifterPortfolioMarketsData = {
|
|
106
|
+
morphoMarketsData: {},
|
|
107
|
+
morphoMidnightMarketsData: {},
|
|
108
|
+
compoundV3MarketsData: {},
|
|
109
|
+
sparkMarketsData: {},
|
|
110
|
+
aaveV3MarketsData: {},
|
|
111
|
+
aaveV2MarketsData: {},
|
|
112
|
+
compoundV2MarketsData: {},
|
|
113
|
+
crvUsdMarketsData: {},
|
|
114
|
+
llamaLendMarketsData: {},
|
|
115
|
+
liquityV2MarketsData: {},
|
|
116
|
+
aaveV4SpokesData: {},
|
|
117
|
+
fluidMarketsData: {},
|
|
118
|
+
makerMarketsData: {},
|
|
119
|
+
};
|
|
120
|
+
const makerCdps: Record<string, CdpInfo[]> = {};
|
|
121
|
+
const positions: PortfolioPositionsData = {};
|
|
122
|
+
const stakingPositions: Record<string, any> = {};
|
|
123
|
+
const rewardsData: Record<string, any> = {};
|
|
124
|
+
|
|
125
|
+
for (const address of addresses) {
|
|
126
|
+
positions[lower(address)] = {
|
|
127
|
+
aaveV3: {},
|
|
128
|
+
aaveV4: {},
|
|
129
|
+
morphoBlue: {},
|
|
130
|
+
morphoMidnight: {},
|
|
131
|
+
compoundV3: {},
|
|
132
|
+
spark: {},
|
|
133
|
+
maker: {},
|
|
134
|
+
aaveV2: {},
|
|
135
|
+
compoundV2: {},
|
|
136
|
+
liquity: {},
|
|
137
|
+
crvUsd: {},
|
|
138
|
+
llamaLend: {},
|
|
139
|
+
fluid: { error: '', data: {} },
|
|
140
|
+
};
|
|
141
|
+
if (fetchStaking) {
|
|
142
|
+
stakingPositions[lower(address)] = {
|
|
143
|
+
aaveV3: {}, morphoBlue: {}, liquity: {}, liquityV2: {}, fluid: { error: '', data: {} },
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
if (fetchRewards) {
|
|
147
|
+
rewardsData[lower(address)] = {
|
|
148
|
+
merkl: {}, aaveV3: {}, spark: {}, spk: {}, king: {}, ethena: {}, uniswap: {},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const run = async <T>(label: string, fetch: () => Promise<T>, store: (data: T) => void, onError: (err: { error: string, data: null }) => void) => {
|
|
154
|
+
try {
|
|
155
|
+
store(await fetch());
|
|
156
|
+
} catch (error) {
|
|
157
|
+
console.error(`Error fetching ${label}:`, error);
|
|
158
|
+
onError({ error: `Error fetching ${label}`, data: null });
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const perAddress = <M>(list: M[], task: (market: M, address: EthAddress) => Promise<void>) => list.map((m) => addresses.map((a) => task(m, a))).flat();
|
|
163
|
+
|
|
164
|
+
const batchRewards = (key: string, label: string, fetch: () => Promise<Record<string, any>>, enabled = true) => (async () => {
|
|
165
|
+
if (!enabled) {
|
|
166
|
+
for (const address of addresses) rewardsData[lower(address)][key] = { error: '', data: [] };
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const result = await fetch();
|
|
171
|
+
for (const address of addresses) rewardsData[lower(address)][key] = { error: '', data: result[lower(address)] || [] };
|
|
172
|
+
} catch (error) {
|
|
173
|
+
console.error(`Error fetching ${label}:`, error);
|
|
174
|
+
for (const address of addresses) rewardsData[lower(address)][key] = { error: `Error fetching ${label}`, data: null };
|
|
175
|
+
}
|
|
176
|
+
})();
|
|
177
|
+
|
|
178
|
+
await Promise.allSettled([
|
|
179
|
+
...morphoMarkets.map(async (m) => { markets.morphoMarketsData[m.value] = await _getMorphoBluePortfolioMarketData(client, network, m, blockNumber); }),
|
|
180
|
+
...morphoMidnightMarkets.map(async (m) => { markets.morphoMidnightMarketsData[m.value] = await _getMorphoMidnightMarketData(client, network, m, blockNumber); }),
|
|
181
|
+
...compoundV3Markets.map(async (m) => { markets.compoundV3MarketsData[m.value] = await _getCompoundV3MarketsData(client, network, m, defaultClient, blockNumber, blockTimestamp); }),
|
|
182
|
+
...sparkMarkets.map(async (m) => { markets.sparkMarketsData[m.value] = await _getSparkMarketsData(client, network, m, blockNumber); }),
|
|
183
|
+
...aaveV3Markets.map(async (m) => { markets.aaveV3MarketsData[m.value] = await _getAaveV3MarketData(client, network, m, blockNumber, blockTimestamp); }),
|
|
184
|
+
...aaveV4Spokes.map(async (s) => { markets.aaveV4SpokesData[s.value] = await _getAaveV4SpokeData(client, network, s, blockNumber, blockTimestamp); }),
|
|
185
|
+
...aaveV2Markets.map(async (m) => { markets.aaveV2MarketsData[m.value] = await _getAaveV2MarketsData(client, network, m, blockNumber); }),
|
|
186
|
+
...compoundV2Markets.map(async (m) => { markets.compoundV2MarketsData[m.value] = await _getCompoundV2MarketsData(client, network, blockNumber); }),
|
|
187
|
+
...crvUsdMarkets.map(async (m) => { markets.crvUsdMarketsData[m.value] = await _getCurveUsdGlobalData(client, network, m, blockNumber); }),
|
|
188
|
+
...llamaLendMarkets.map(async (m) => { markets.llamaLendMarketsData[m.value] = await _getLlamaLendGlobalData(client, network, m, blockNumber); }),
|
|
189
|
+
...liquityV2Markets.map(async (m) => { markets.liquityV2MarketsData[m.value] = await _getLiquityV2MarketData(client, network, m, blockNumber); }),
|
|
190
|
+
(async () => {
|
|
191
|
+
if (!fetchFluid || !fetchFluidMarkets) return;
|
|
192
|
+
try { markets.fluidMarketsData = await _getAllFluidMarketDataPortfolio(client, network, blockNumber, blockTimestamp); } catch (error) { console.error('Error fetching Fluid markets data:', error); }
|
|
193
|
+
})(),
|
|
194
|
+
(async () => {
|
|
195
|
+
if (!fetchMaker) return;
|
|
196
|
+
try { markets.makerMarketsData = await _getMakerIlksData(client, network, MakerActiveIlks, blockNumber); } catch (error) { console.error('Error fetching Maker ilks data:', error); }
|
|
197
|
+
})(),
|
|
198
|
+
|
|
199
|
+
...addresses.map(async (address) => {
|
|
200
|
+
if (!fetchMaker) return;
|
|
201
|
+
makerCdps[lower(address)] = await _getUserCdps(client, network, address, blockNumber);
|
|
202
|
+
}),
|
|
203
|
+
...addresses.map((address) => fetchFluid && run(
|
|
204
|
+
`Fluid positions for address ${address}`,
|
|
205
|
+
() => _getUserPositionsPortfolio(client, network, address, blockNumber),
|
|
206
|
+
(userPositions) => {
|
|
207
|
+
for (const position of userPositions) {
|
|
208
|
+
if (position.userData && positive(position.userData.suppliedUsd)) positions[lower(address)].fluid.data[position.userData.nftId] = position.userData;
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
(err) => { positions[lower(address)].fluid = { error: err.error, data: {} }; },
|
|
212
|
+
)),
|
|
213
|
+
|
|
214
|
+
...(fetchStaking ? [
|
|
215
|
+
...addresses.map((address) => fetchFluid && run(
|
|
216
|
+
`Fluid lend data for address ${address}`,
|
|
217
|
+
() => _getAllUserEarnPositionsWithFTokens(client, network, address, blockNumber),
|
|
218
|
+
(data) => { stakingPositions[lower(address)].fluid = data; },
|
|
219
|
+
(err) => { stakingPositions[lower(address)].fluid = err; },
|
|
220
|
+
)),
|
|
221
|
+
...addresses.map((address) => fetchLiquity && run(
|
|
222
|
+
`Liquity staking data for address ${address}`,
|
|
223
|
+
() => getLiquityStakingData(client, network, address, blockNumber),
|
|
224
|
+
(data) => { stakingPositions[lower(address)].liquity = data; },
|
|
225
|
+
(err) => { stakingPositions[lower(address)].liquity = err; },
|
|
226
|
+
)),
|
|
227
|
+
...addresses.map((address) => has(PortfolioProtocol.AaveV3) && isMainnet && run(
|
|
228
|
+
`Aave V3 staking data for address ${address}`,
|
|
229
|
+
() => getStakeAaveData(client, network, address, blockNumber),
|
|
230
|
+
(data) => { stakingPositions[lower(address)].aaveV3 = data; },
|
|
231
|
+
(err) => { stakingPositions[lower(address)].aaveV3 = err; },
|
|
232
|
+
)),
|
|
233
|
+
...addresses.map((address) => has(PortfolioProtocol.AaveV3) && isMainnet && run(
|
|
234
|
+
`Umbrella staking data for address ${address}`,
|
|
235
|
+
() => getUmbrellaData(client, network, address, blockNumber),
|
|
236
|
+
(data) => { stakingPositions[lower(address)].umbrella = data; },
|
|
237
|
+
(err) => { stakingPositions[lower(address)].umbrella = err; },
|
|
238
|
+
)),
|
|
239
|
+
...perAddress(liquityV2StakingMarkets, (market, address) => run(
|
|
240
|
+
`Liquity V2 staking data for address ${address}, market ${market.value}`,
|
|
241
|
+
() => getLiquityV2Staking(client, network, market.value, address, blockNumber),
|
|
242
|
+
(data) => { stakingPositions[lower(address)].liquityV2[market.value] = { error: '', data }; },
|
|
243
|
+
(err) => { stakingPositions[lower(address)].liquityV2[market.value] = err; },
|
|
244
|
+
)),
|
|
245
|
+
] : []),
|
|
246
|
+
|
|
247
|
+
...(fetchRewards ? [
|
|
248
|
+
batchRewards('king', 'King rewards data', () => getKingRewards(client, network, addresses, blockNumber), isMainnet),
|
|
249
|
+
batchRewards('uniswap', 'Uniswap rewards data', () => getUniswapRewards(client, network, addresses, blockNumber), isMainnet),
|
|
250
|
+
batchRewards('spk', 'Spark Airdrop rewards data', () => fetchSparkAirdropRewards(client, network, addresses, blockNumber), isMainnet && has(PortfolioProtocol.Spark)),
|
|
251
|
+
batchRewards('ethena', 'Ethena Airdrop rewards data', () => fetchEthenaAirdropRewards(addresses), isMainnet),
|
|
252
|
+
...addresses.map((address) => run(
|
|
253
|
+
`Merkl rewards data for address ${address}`,
|
|
254
|
+
() => getMerklUnclaimedRewards(address, network),
|
|
255
|
+
(data) => { rewardsData[lower(address)].merkl = { error: '', data }; },
|
|
256
|
+
(err) => { rewardsData[lower(address)].merkl = err; },
|
|
257
|
+
)),
|
|
258
|
+
...perAddress(aaveV3Markets, (market, address) => run(
|
|
259
|
+
`Aave V3 rewards data for address ${address}, market ${market.value}`,
|
|
260
|
+
() => getUnclaimedRewardsForAllMarkets(client, network, address, market.providerAddress, blockNumber),
|
|
261
|
+
(data) => { rewardsData[lower(address)].aaveV3[market.value] = { error: '', data }; },
|
|
262
|
+
(err) => { rewardsData[lower(address)].aaveV3[market.value] = err; },
|
|
263
|
+
)),
|
|
264
|
+
...perAddress(sparkMarkets, (market, address) => {
|
|
265
|
+
if (!isMainnet) {
|
|
266
|
+
rewardsData[lower(address)].spark[market.value] = { error: '', data: [] };
|
|
267
|
+
return Promise.resolve();
|
|
268
|
+
}
|
|
269
|
+
return run(
|
|
270
|
+
`Spark rewards data for address ${address}, market ${market.value}`,
|
|
271
|
+
() => fetchSparkRewards(client, network, address, market.providerAddress, blockNumber),
|
|
272
|
+
(data) => { rewardsData[lower(address)].spark[market.value] = { error: '', data }; },
|
|
273
|
+
(err) => { rewardsData[lower(address)].spark[market.value] = err; },
|
|
274
|
+
);
|
|
275
|
+
}),
|
|
276
|
+
] : []),
|
|
277
|
+
]);
|
|
278
|
+
|
|
279
|
+
await Promise.all([
|
|
280
|
+
...perAddress(aaveV3Markets, (market, address) => run(
|
|
281
|
+
`AaveV3 account data for address ${address} on market ${market.value}`,
|
|
282
|
+
() => _getAaveV3AccountData(client, network, address, { selectedMarket: market, ...markets.aaveV3MarketsData[market.value] }, blockNumber),
|
|
283
|
+
(data) => { if (returnEmptyEModePositions || positive(data.suppliedUsd)) positions[lower(address)].aaveV3[market.value] = { error: '', data }; },
|
|
284
|
+
(err) => { positions[lower(address)].aaveV3[market.value] = err; },
|
|
285
|
+
)),
|
|
286
|
+
...perAddress(sparkMarkets, (market, address) => run(
|
|
287
|
+
`Spark account data for address ${address} on market ${market.value}`,
|
|
288
|
+
() => _getSparkAccountData(client, network, address, { selectedMarket: market, assetsData: markets.sparkMarketsData[market.value].assetsData, eModeCategoriesData: markets.sparkMarketsData[market.value].eModeCategoriesData }, blockNumber),
|
|
289
|
+
(data) => { if (returnEmptyEModePositions || positive(data.suppliedUsd)) positions[lower(address)].spark[market.value] = { error: '', data }; },
|
|
290
|
+
(err) => { positions[lower(address)].spark[market.value] = err; },
|
|
291
|
+
)),
|
|
292
|
+
...perAddress(aaveV4Spokes, (spoke, address) => run(
|
|
293
|
+
`AaveV4 account data for address ${address} on spoke ${spoke.value}`,
|
|
294
|
+
() => _getAaveV4AccountData(client, network, markets.aaveV4SpokesData[spoke.value], address, blockNumber),
|
|
295
|
+
(data) => { if (positive(data.suppliedUsd)) positions[lower(address)].aaveV4[spoke.value] = { error: '', data }; },
|
|
296
|
+
(err) => { positions[lower(address)].aaveV4[spoke.value] = err; },
|
|
297
|
+
)),
|
|
298
|
+
...perAddress(morphoMarkets, (market, address) => run(
|
|
299
|
+
`MorphoBlue account data for address ${address} on market ${market.value}`,
|
|
300
|
+
() => _getMorphoBlueAccountData(client, network, address, market, markets.morphoMarketsData[market.value], blockNumber),
|
|
301
|
+
(data) => { if (positive(data.suppliedUsd)) positions[lower(address)].morphoBlue[market.value] = { error: '', data }; },
|
|
302
|
+
(err) => { positions[lower(address)].morphoBlue[market.value] = err; },
|
|
303
|
+
)),
|
|
304
|
+
...(fetchStaking ? perAddress(morphoMarkets, (market, address) => run(
|
|
305
|
+
`MorphoBlue earn data for address ${address} on market ${market.value}`,
|
|
306
|
+
() => getMorphoEarn(client, network, address, market, markets.morphoMarketsData[market.value], blockNumber),
|
|
307
|
+
(data) => { if (data && positive(data.amount)) stakingPositions[lower(address)].morphoBlue[market.value] = { error: '', data }; },
|
|
308
|
+
(err) => { stakingPositions[lower(address)].morphoBlue[market.value] = err; },
|
|
309
|
+
)) : []),
|
|
310
|
+
...perAddress(morphoMidnightMarkets, (market, address) => {
|
|
311
|
+
if (!markets.morphoMidnightMarketsData[market.value]?.isCreated) return Promise.resolve();
|
|
312
|
+
return run(
|
|
313
|
+
`MorphoMidnight account data for address ${address} on market ${market.value}`,
|
|
314
|
+
() => _getMorphoMidnightAccountData(client, network, address, market, markets.morphoMidnightMarketsData[market.value], blockNumber),
|
|
315
|
+
(data) => { if (positive(data.suppliedUsd)) positions[lower(address)].morphoMidnight[market.value] = { error: '', data }; },
|
|
316
|
+
(err) => { positions[lower(address)].morphoMidnight[market.value] = err; },
|
|
317
|
+
);
|
|
318
|
+
}),
|
|
319
|
+
...perAddress(compoundV3Markets, (market, address) => run(
|
|
320
|
+
`CompoundV3 account data for address ${address} on market ${market.value}`,
|
|
321
|
+
() => _getCompoundV3AccountData(client, network, address, ZERO_ADDRESS, { selectedMarket: market, assetsData: markets.compoundV3MarketsData[market.value].assetsData }, blockNumber),
|
|
322
|
+
(data) => { if (positive(data.suppliedUsd)) positions[lower(address)].compoundV3[market.value] = { error: '', data }; },
|
|
323
|
+
(err) => { positions[lower(address)].compoundV3[market.value] = err; },
|
|
324
|
+
)),
|
|
325
|
+
...perAddress(compoundV2Markets, (market, address) => run(
|
|
326
|
+
`CompoundV2 account data for address ${address}`,
|
|
327
|
+
() => _getCompoundV2AccountData(client, network, address, markets.compoundV2MarketsData[market.value].assetsData, blockNumber),
|
|
328
|
+
(data) => { if (positive(data.suppliedUsd)) positions[lower(address)].compoundV2[market.value] = { error: '', data }; },
|
|
329
|
+
(err) => { positions[lower(address)].compoundV2[market.value] = err; },
|
|
330
|
+
)),
|
|
331
|
+
...perAddress(aaveV2Markets, (market, address) => run(
|
|
332
|
+
`AaveV2 account data for address ${address}`,
|
|
333
|
+
() => _getAaveV2AccountData(client, network, address, markets.aaveV2MarketsData[market.value].assetsData, market, blockNumber),
|
|
334
|
+
(data) => { if (positive(data.suppliedUsd)) positions[lower(address)].aaveV2[market.value] = { error: '', data }; },
|
|
335
|
+
(err) => { positions[lower(address)].aaveV2[market.value] = err; },
|
|
336
|
+
)),
|
|
337
|
+
...perAddress(crvUsdMarkets, (market, address) => run(
|
|
338
|
+
`Curve USD account data for address ${address} on market ${market.value}`,
|
|
339
|
+
() => _getCurveUsdUserData(client, network, address, market, markets.crvUsdMarketsData[market.value].activeBand, markets.crvUsdMarketsData[market.value].borrowRate, blockNumber),
|
|
340
|
+
(data) => { if (positive(data.suppliedUsd) || positive(data.borrowedUsd)) positions[lower(address)].crvUsd[market.value] = { error: '', data }; },
|
|
341
|
+
(err) => { positions[lower(address)].crvUsd[market.value] = err; },
|
|
342
|
+
)),
|
|
343
|
+
...perAddress(llamaLendMarkets, (market, address) => run(
|
|
344
|
+
`LlamaLend account data for address ${address} on market ${market.value}`,
|
|
345
|
+
() => _getLlamaLendUserData(client, network, address, market, markets.llamaLendMarketsData[market.value], blockNumber),
|
|
346
|
+
(data) => {
|
|
347
|
+
if (positive(data.suppliedUsd) || positive(data.borrowedUsd)) {
|
|
348
|
+
positions[lower(address)].llamaLend[market.value] = { error: '', data: { ...data, borrowRate: markets.llamaLendMarketsData[market.value].borrowRate } };
|
|
349
|
+
}
|
|
350
|
+
},
|
|
351
|
+
(err) => { positions[lower(address)].llamaLend[market.value] = err; },
|
|
352
|
+
)),
|
|
353
|
+
...addresses.map((address) => (makerCdps[lower(address)] || []).map((cdpInfo) => run(
|
|
354
|
+
`Maker CDP data for address ${address} with ID ${cdpInfo.id}`,
|
|
355
|
+
() => _getMakerCdpData(client, network, cdpInfo, markets.makerMarketsData[cdpInfo.ilkLabel], blockNumber),
|
|
356
|
+
(data) => { if (data) positions[lower(address)].maker[cdpInfo.id] = { error: '', data }; },
|
|
357
|
+
(err) => { positions[lower(address)].maker[cdpInfo.id] = err; },
|
|
358
|
+
))).flat(),
|
|
359
|
+
...addresses.map((address) => fetchLiquity && run(
|
|
360
|
+
`Liquity trove info for address ${address}`,
|
|
361
|
+
() => _getLiquityTroveInfo(client, network, address, blockNumber),
|
|
362
|
+
(data) => { if (positive(data.collateral)) positions[lower(address)].liquity = { error: '', data }; },
|
|
363
|
+
(err) => { positions[lower(address)].liquity = err; },
|
|
364
|
+
)),
|
|
365
|
+
...(fetchStaking && has(PortfolioProtocol.LiquityV2) ? addresses.map((address) => {
|
|
366
|
+
if (!isMainnet) {
|
|
367
|
+
stakingPositions[lower(address)].liquityV2SBoldYBold = { error: '', data: null };
|
|
368
|
+
return Promise.resolve();
|
|
369
|
+
}
|
|
370
|
+
return run(
|
|
371
|
+
`sBold/yBold data for address ${address}`,
|
|
372
|
+
() => getLiquitySAndYBold(client, network, stakingPositions[lower(address)].liquityV2, address, blockNumber),
|
|
373
|
+
(data) => { stakingPositions[lower(address)].liquityV2SBoldYBold = { error: '', data }; },
|
|
374
|
+
(err) => { stakingPositions[lower(address)].liquityV2SBoldYBold = err; },
|
|
375
|
+
);
|
|
376
|
+
}) : []),
|
|
377
|
+
]);
|
|
378
|
+
|
|
379
|
+
return {
|
|
380
|
+
positions,
|
|
381
|
+
stakingPositions,
|
|
382
|
+
rewardsData,
|
|
383
|
+
markets,
|
|
384
|
+
};
|
|
385
|
+
}
|
package/src/portfolio/index.ts
CHANGED
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
|
+
);
|