@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.
Files changed (208) hide show
  1. package/cjs/aaveV2/index.d.ts +4 -4
  2. package/cjs/aaveV2/index.js +7 -7
  3. package/cjs/aaveV3/index.d.ts +4 -3
  4. package/cjs/aaveV3/index.js +14 -10
  5. package/cjs/aaveV3/merkl.d.ts +5 -1
  6. package/cjs/aaveV3/merkl.js +8 -3
  7. package/cjs/aaveV4/index.d.ts +4 -3
  8. package/cjs/aaveV4/index.js +19 -16
  9. package/cjs/aaveV4/merkl.d.ts +10 -2
  10. package/cjs/aaveV4/merkl.js +15 -6
  11. package/cjs/claiming/aaveV3.d.ts +2 -2
  12. package/cjs/claiming/aaveV3.js +5 -4
  13. package/cjs/claiming/king.d.ts +2 -2
  14. package/cjs/claiming/king.js +3 -2
  15. package/cjs/claiming/spark.d.ts +3 -3
  16. package/cjs/claiming/spark.js +8 -7
  17. package/cjs/claiming/uniswap.d.ts +2 -2
  18. package/cjs/claiming/uniswap.js +3 -2
  19. package/cjs/compoundV2/index.d.ts +4 -4
  20. package/cjs/compoundV2/index.js +9 -9
  21. package/cjs/compoundV3/index.d.ts +5 -4
  22. package/cjs/compoundV3/index.js +17 -13
  23. package/cjs/compoundV3/merkl.d.ts +1 -1
  24. package/cjs/compoundV3/merkl.js +2 -5
  25. package/cjs/curveUsd/index.d.ts +5 -5
  26. package/cjs/curveUsd/index.js +17 -17
  27. package/cjs/fluid/index.d.ts +23 -22
  28. package/cjs/fluid/index.js +75 -72
  29. package/cjs/fluid/merkl.d.ts +5 -3
  30. package/cjs/fluid/merkl.js +11 -6
  31. package/cjs/helpers/aaveHelpers/index.js +1 -1
  32. package/cjs/helpers/aaveV4Helpers/index.js +14 -2
  33. package/cjs/helpers/compoundHelpers/index.js +2 -2
  34. package/cjs/helpers/curveUsdHelpers/index.js +1 -1
  35. package/cjs/helpers/fluidHelpers/index.js +1 -1
  36. package/cjs/helpers/liquityV2Helpers/index.js +1 -1
  37. package/cjs/helpers/llamaLendHelpers/index.js +1 -1
  38. package/cjs/helpers/morphoBlueHelpers/index.js +1 -1
  39. package/cjs/helpers/morphoMidnightHelpers/index.js +1 -1
  40. package/cjs/helpers/sparkHelpers/index.js +1 -1
  41. package/cjs/liquity/index.d.ts +4 -4
  42. package/cjs/liquity/index.js +23 -23
  43. package/cjs/liquityV2/index.d.ts +10 -10
  44. package/cjs/liquityV2/index.js +59 -59
  45. package/cjs/llamaLend/index.d.ts +5 -5
  46. package/cjs/llamaLend/index.js +13 -13
  47. package/cjs/maker/index.d.ts +6 -6
  48. package/cjs/maker/index.js +16 -16
  49. package/cjs/markets/morphoBlue/index.d.ts +2 -0
  50. package/cjs/markets/morphoBlue/index.js +19 -2
  51. package/cjs/moneymarket/moneymarketCommonService.js +14 -3
  52. package/cjs/morphoBlue/index.d.ts +7 -7
  53. package/cjs/morphoBlue/index.js +28 -26
  54. package/cjs/morphoBlue/merkl.d.ts +5 -3
  55. package/cjs/morphoBlue/merkl.js +6 -8
  56. package/cjs/morphoMidnight/index.d.ts +5 -5
  57. package/cjs/morphoMidnight/index.js +18 -18
  58. package/cjs/portfolio/customDeFiData.d.ts +3 -0
  59. package/cjs/portfolio/customDeFiData.js +267 -0
  60. package/cjs/portfolio/index.d.ts +1 -0
  61. package/cjs/portfolio/index.js +1 -0
  62. package/cjs/services/merkl.d.ts +46 -2
  63. package/cjs/services/merkl.js +190 -19
  64. package/cjs/services/priceService.d.ts +12 -12
  65. package/cjs/services/priceService.js +30 -29
  66. package/cjs/services/viem.d.ts +10 -2
  67. package/cjs/services/viem.js +27 -1
  68. package/cjs/spark/index.d.ts +4 -4
  69. package/cjs/spark/index.js +9 -9
  70. package/cjs/staking/staking.js +3 -1
  71. package/cjs/types/aaveV4.d.ts +1 -0
  72. package/cjs/types/common.d.ts +1 -0
  73. package/cjs/types/common.js +1 -0
  74. package/cjs/types/merkl.d.ts +18 -0
  75. package/cjs/types/morphoBlue.d.ts +1 -0
  76. package/cjs/types/morphoBlue.js +1 -0
  77. package/cjs/types/portfolio.d.ts +37 -0
  78. package/cjs/types/portfolio.js +18 -0
  79. package/cjs/umbrella/index.d.ts +2 -2
  80. package/cjs/umbrella/index.js +5 -4
  81. package/esm/aaveV2/index.d.ts +4 -4
  82. package/esm/aaveV2/index.js +8 -8
  83. package/esm/aaveV3/index.d.ts +4 -3
  84. package/esm/aaveV3/index.js +15 -11
  85. package/esm/aaveV3/merkl.d.ts +5 -1
  86. package/esm/aaveV3/merkl.js +9 -4
  87. package/esm/aaveV4/index.d.ts +4 -3
  88. package/esm/aaveV4/index.js +20 -17
  89. package/esm/aaveV4/merkl.d.ts +10 -2
  90. package/esm/aaveV4/merkl.js +16 -7
  91. package/esm/claiming/aaveV3.d.ts +2 -2
  92. package/esm/claiming/aaveV3.js +5 -4
  93. package/esm/claiming/king.d.ts +2 -2
  94. package/esm/claiming/king.js +3 -2
  95. package/esm/claiming/spark.d.ts +3 -3
  96. package/esm/claiming/spark.js +8 -7
  97. package/esm/claiming/uniswap.d.ts +2 -2
  98. package/esm/claiming/uniswap.js +3 -2
  99. package/esm/compoundV2/index.d.ts +4 -4
  100. package/esm/compoundV2/index.js +9 -9
  101. package/esm/compoundV3/index.d.ts +5 -4
  102. package/esm/compoundV3/index.js +19 -15
  103. package/esm/compoundV3/merkl.d.ts +1 -1
  104. package/esm/compoundV3/merkl.js +3 -6
  105. package/esm/curveUsd/index.d.ts +5 -5
  106. package/esm/curveUsd/index.js +17 -17
  107. package/esm/fluid/index.d.ts +23 -22
  108. package/esm/fluid/index.js +76 -73
  109. package/esm/fluid/merkl.d.ts +5 -3
  110. package/esm/fluid/merkl.js +12 -7
  111. package/esm/helpers/aaveHelpers/index.js +1 -1
  112. package/esm/helpers/aaveV4Helpers/index.js +15 -3
  113. package/esm/helpers/compoundHelpers/index.js +2 -2
  114. package/esm/helpers/curveUsdHelpers/index.js +1 -1
  115. package/esm/helpers/fluidHelpers/index.js +1 -1
  116. package/esm/helpers/liquityV2Helpers/index.js +1 -1
  117. package/esm/helpers/llamaLendHelpers/index.js +1 -1
  118. package/esm/helpers/morphoBlueHelpers/index.js +1 -1
  119. package/esm/helpers/morphoMidnightHelpers/index.js +1 -1
  120. package/esm/helpers/sparkHelpers/index.js +1 -1
  121. package/esm/liquity/index.d.ts +4 -4
  122. package/esm/liquity/index.js +23 -23
  123. package/esm/liquityV2/index.d.ts +10 -10
  124. package/esm/liquityV2/index.js +60 -60
  125. package/esm/llamaLend/index.d.ts +5 -5
  126. package/esm/llamaLend/index.js +13 -13
  127. package/esm/maker/index.d.ts +6 -6
  128. package/esm/maker/index.js +16 -16
  129. package/esm/markets/morphoBlue/index.d.ts +2 -0
  130. package/esm/markets/morphoBlue/index.js +16 -0
  131. package/esm/moneymarket/moneymarketCommonService.js +14 -3
  132. package/esm/morphoBlue/index.d.ts +7 -7
  133. package/esm/morphoBlue/index.js +29 -27
  134. package/esm/morphoBlue/merkl.d.ts +5 -3
  135. package/esm/morphoBlue/merkl.js +7 -9
  136. package/esm/morphoMidnight/index.d.ts +5 -5
  137. package/esm/morphoMidnight/index.js +18 -18
  138. package/esm/portfolio/customDeFiData.d.ts +3 -0
  139. package/esm/portfolio/customDeFiData.js +261 -0
  140. package/esm/portfolio/index.d.ts +1 -0
  141. package/esm/portfolio/index.js +1 -0
  142. package/esm/services/merkl.d.ts +46 -2
  143. package/esm/services/merkl.js +180 -18
  144. package/esm/services/priceService.d.ts +12 -12
  145. package/esm/services/priceService.js +31 -30
  146. package/esm/services/viem.d.ts +10 -2
  147. package/esm/services/viem.js +25 -0
  148. package/esm/spark/index.d.ts +4 -4
  149. package/esm/spark/index.js +10 -10
  150. package/esm/staking/staking.js +3 -1
  151. package/esm/types/aaveV4.d.ts +1 -0
  152. package/esm/types/common.d.ts +1 -0
  153. package/esm/types/common.js +1 -0
  154. package/esm/types/merkl.d.ts +18 -0
  155. package/esm/types/morphoBlue.d.ts +1 -0
  156. package/esm/types/morphoBlue.js +1 -0
  157. package/esm/types/portfolio.d.ts +37 -0
  158. package/esm/types/portfolio.js +17 -1
  159. package/esm/umbrella/index.d.ts +2 -2
  160. package/esm/umbrella/index.js +5 -4
  161. package/package.json +2 -2
  162. package/src/aaveV2/index.ts +7 -7
  163. package/src/aaveV3/index.ts +15 -11
  164. package/src/aaveV3/merkl.ts +9 -4
  165. package/src/aaveV4/index.ts +19 -16
  166. package/src/aaveV4/merkl.ts +16 -7
  167. package/src/claiming/aaveV3.ts +5 -3
  168. package/src/claiming/king.ts +6 -3
  169. package/src/claiming/spark.ts +9 -6
  170. package/src/claiming/uniswap.ts +4 -3
  171. package/src/compoundV2/index.ts +10 -9
  172. package/src/compoundV3/index.ts +20 -14
  173. package/src/compoundV3/merkl.ts +5 -4
  174. package/src/curveUsd/index.ts +19 -17
  175. package/src/fluid/index.ts +88 -70
  176. package/src/fluid/merkl.ts +12 -7
  177. package/src/helpers/aaveHelpers/index.ts +1 -1
  178. package/src/helpers/aaveV4Helpers/index.ts +16 -2
  179. package/src/helpers/compoundHelpers/index.ts +2 -2
  180. package/src/helpers/curveUsdHelpers/index.ts +1 -1
  181. package/src/helpers/fluidHelpers/index.ts +1 -1
  182. package/src/helpers/liquityV2Helpers/index.ts +1 -1
  183. package/src/helpers/llamaLendHelpers/index.ts +1 -1
  184. package/src/helpers/morphoBlueHelpers/index.ts +1 -1
  185. package/src/helpers/morphoMidnightHelpers/index.ts +1 -1
  186. package/src/helpers/sparkHelpers/index.ts +1 -1
  187. package/src/liquity/index.ts +23 -23
  188. package/src/liquityV2/index.ts +64 -56
  189. package/src/llamaLend/index.ts +15 -13
  190. package/src/maker/index.ts +19 -16
  191. package/src/markets/morphoBlue/index.ts +16 -0
  192. package/src/moneymarket/moneymarketCommonService.ts +15 -3
  193. package/src/morphoBlue/index.ts +23 -20
  194. package/src/morphoBlue/merkl.ts +9 -6
  195. package/src/morphoMidnight/index.ts +13 -13
  196. package/src/portfolio/customDeFiData.ts +385 -0
  197. package/src/portfolio/index.ts +1 -0
  198. package/src/services/merkl.ts +209 -19
  199. package/src/services/priceService.ts +33 -30
  200. package/src/services/viem.ts +16 -0
  201. package/src/spark/index.ts +11 -8
  202. package/src/staking/staking.ts +2 -1
  203. package/src/types/aaveV4.ts +1 -0
  204. package/src/types/common.ts +1 -0
  205. package/src/types/merkl.ts +20 -0
  206. package/src/types/morphoBlue.ts +1 -0
  207. package/src/types/portfolio.ts +40 -0
  208. package/src/umbrella/index.ts +6 -5
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getCustomDeFiData = getCustomDeFiData;
16
+ const decimal_js_1 = __importDefault(require("decimal.js"));
17
+ const common_1 = require("../types/common");
18
+ const markets_1 = require("../markets");
19
+ const types_1 = require("../types");
20
+ const viem_1 = require("../services/viem");
21
+ const constants_1 = require("../constants");
22
+ const aaveV2_1 = require("../aaveV2");
23
+ const aaveV3_1 = require("../aaveV3");
24
+ const aaveV4_1 = require("../aaveV4");
25
+ const compoundV2_1 = require("../compoundV2");
26
+ const compoundV3_1 = require("../compoundV3");
27
+ const spark_1 = require("../spark");
28
+ const curveUsd_1 = require("../curveUsd");
29
+ const llamaLend_1 = require("../llamaLend");
30
+ const morphoBlue_1 = require("../morphoBlue");
31
+ const morphoMidnight_1 = require("../morphoMidnight");
32
+ const maker_1 = require("../maker");
33
+ const liquity_1 = require("../liquity");
34
+ const liquityV2_1 = require("../liquityV2");
35
+ const fluid_1 = require("../fluid");
36
+ const umbrella_1 = require("../umbrella");
37
+ const aaveV3_2 = require("../claiming/aaveV3");
38
+ const spark_2 = require("../claiming/spark");
39
+ const king_1 = require("../claiming/king");
40
+ const ethena_1 = require("../claiming/ethena");
41
+ const uniswap_1 = require("../claiming/uniswap");
42
+ const lower = (address) => address.toLowerCase();
43
+ const positive = (value) => new decimal_js_1.default(value || '0').gt(0);
44
+ const supported = (list, network) => (Object.values(list).filter((m) => m.chainIds.includes(network)));
45
+ function getCustomDeFiData(provider_1, network_1, defaultProvider_1, addresses_1) {
46
+ return __awaiter(this, arguments, void 0, function* (provider, network, defaultProvider, addresses, options = {}) {
47
+ var _a, _b;
48
+ const { protocols = Object.values(types_1.PortfolioProtocol), fetchStaking = false, fetchRewards = false, returnEmptyEModePositions = false, fetchFluidMarkets = false, isSim = false, } = options;
49
+ // JSON-RPC body ends up ~4x the calldata cap; 250k keeps it under the ~2.5MB provider limit.
50
+ const batchSize = (_a = options.batchSize) !== null && _a !== void 0 ? _a : (isSim ? 2000 : 250000);
51
+ const has = (protocol) => protocols.includes(protocol);
52
+ const isMainnet = network === common_1.NetworkNumber.Eth;
53
+ const isFluidSupported = [common_1.NetworkNumber.Eth, common_1.NetworkNumber.Arb, common_1.NetworkNumber.Base, common_1.NetworkNumber.Plasma].includes(network);
54
+ const client = (0, viem_1.getViemProvider)(provider, network, { batch: { multicall: { batchSize } } });
55
+ const defaultClient = (0, viem_1.getViemProvider)(defaultProvider, network, { batch: { multicall: { batchSize } } });
56
+ // Every fetch below takes the block explicitly and passes it to each of its contract reads.
57
+ // Time-keyed sources (Merkl rewards) need the block's timestamp instead, resolved once here (no
58
+ // RPC call for 'latest') and handed to the market fetches so they don't each look it up.
59
+ const blockNumber = (_b = options.blockNumber) !== null && _b !== void 0 ? _b : 'latest';
60
+ const blockTimestamp = yield (0, viem_1.getBlockTimestamp)(client, blockNumber);
61
+ const aaveV3Markets = has(types_1.PortfolioProtocol.AaveV3)
62
+ ? [types_1.AaveVersions.AaveV3, types_1.AaveVersions.AaveV3Lido, types_1.AaveVersions.AaveV3Etherfi].map((v) => (0, markets_1.AaveMarkets)(network)[v]).filter((m) => m.chainIds.includes(network))
63
+ : [];
64
+ const aaveV2Markets = has(types_1.PortfolioProtocol.AaveV2) ? [(0, markets_1.AaveMarkets)(network)[types_1.AaveVersions.AaveV2]].filter((m) => m.chainIds.includes(network)) : [];
65
+ const aaveV4Spokes = has(types_1.PortfolioProtocol.AaveV4) ? supported((0, markets_1.AaveV4Spokes)(network), network) : [];
66
+ const compoundV3Markets = has(types_1.PortfolioProtocol.CompoundV3) ? supported((0, markets_1.CompoundMarkets)(network), network).filter((m) => m.value !== types_1.CompoundVersions.CompoundV2) : [];
67
+ const compoundV2Markets = has(types_1.PortfolioProtocol.CompoundV2) ? [(0, markets_1.CompoundMarkets)(network)[types_1.CompoundVersions.CompoundV2]].filter((m) => m.chainIds.includes(network)) : [];
68
+ const sparkMarkets = has(types_1.PortfolioProtocol.Spark) ? supported((0, markets_1.SparkMarkets)(network), network) : [];
69
+ const morphoMarkets = has(types_1.PortfolioProtocol.MorphoBlue) ? supported((0, markets_1.MorphoBlueMarkets)(network), network) : [];
70
+ const morphoMidnightMarkets = has(types_1.PortfolioProtocol.MorphoMidnight) ? supported((0, markets_1.MorphoMidnightMarkets)(network), network) : [];
71
+ const crvUsdMarkets = has(types_1.PortfolioProtocol.CrvUsd) ? supported((0, markets_1.CrvUsdMarkets)(network), network) : [];
72
+ const llamaLendMarkets = has(types_1.PortfolioProtocol.LlamaLend) && [common_1.NetworkNumber.Eth, common_1.NetworkNumber.Arb].includes(network) ? supported((0, markets_1.LlamaLendMarkets)(network), network) : [];
73
+ const liquityV2Markets = has(types_1.PortfolioProtocol.LiquityV2) && isMainnet ? Object.values((0, markets_1.LiquityV2Markets)(network)) : [];
74
+ const liquityV2StakingMarkets = liquityV2Markets.filter((m) => !m.isLegacy);
75
+ const fetchMaker = has(types_1.PortfolioProtocol.Maker) && isMainnet;
76
+ const fetchLiquity = has(types_1.PortfolioProtocol.Liquity) && isMainnet;
77
+ const fetchFluid = has(types_1.PortfolioProtocol.Fluid) && isFluidSupported;
78
+ const markets = {
79
+ morphoMarketsData: {},
80
+ morphoMidnightMarketsData: {},
81
+ compoundV3MarketsData: {},
82
+ sparkMarketsData: {},
83
+ aaveV3MarketsData: {},
84
+ aaveV2MarketsData: {},
85
+ compoundV2MarketsData: {},
86
+ crvUsdMarketsData: {},
87
+ llamaLendMarketsData: {},
88
+ liquityV2MarketsData: {},
89
+ aaveV4SpokesData: {},
90
+ fluidMarketsData: {},
91
+ makerMarketsData: {},
92
+ };
93
+ const makerCdps = {};
94
+ const positions = {};
95
+ const stakingPositions = {};
96
+ const rewardsData = {};
97
+ for (const address of addresses) {
98
+ positions[lower(address)] = {
99
+ aaveV3: {},
100
+ aaveV4: {},
101
+ morphoBlue: {},
102
+ morphoMidnight: {},
103
+ compoundV3: {},
104
+ spark: {},
105
+ maker: {},
106
+ aaveV2: {},
107
+ compoundV2: {},
108
+ liquity: {},
109
+ crvUsd: {},
110
+ llamaLend: {},
111
+ fluid: { error: '', data: {} },
112
+ };
113
+ if (fetchStaking) {
114
+ stakingPositions[lower(address)] = {
115
+ aaveV3: {}, morphoBlue: {}, liquity: {}, liquityV2: {}, fluid: { error: '', data: {} },
116
+ };
117
+ }
118
+ if (fetchRewards) {
119
+ rewardsData[lower(address)] = {
120
+ merkl: {}, aaveV3: {}, spark: {}, spk: {}, king: {}, ethena: {}, uniswap: {},
121
+ };
122
+ }
123
+ }
124
+ const run = (label, fetch, store, onError) => __awaiter(this, void 0, void 0, function* () {
125
+ try {
126
+ store(yield fetch());
127
+ }
128
+ catch (error) {
129
+ console.error(`Error fetching ${label}:`, error);
130
+ onError({ error: `Error fetching ${label}`, data: null });
131
+ }
132
+ });
133
+ const perAddress = (list, task) => list.map((m) => addresses.map((a) => task(m, a))).flat();
134
+ const batchRewards = (key, label, fetch, enabled = true) => (() => __awaiter(this, void 0, void 0, function* () {
135
+ if (!enabled) {
136
+ for (const address of addresses)
137
+ rewardsData[lower(address)][key] = { error: '', data: [] };
138
+ return;
139
+ }
140
+ try {
141
+ const result = yield fetch();
142
+ for (const address of addresses)
143
+ rewardsData[lower(address)][key] = { error: '', data: result[lower(address)] || [] };
144
+ }
145
+ catch (error) {
146
+ console.error(`Error fetching ${label}:`, error);
147
+ for (const address of addresses)
148
+ rewardsData[lower(address)][key] = { error: `Error fetching ${label}`, data: null };
149
+ }
150
+ }))();
151
+ yield Promise.allSettled([
152
+ ...morphoMarkets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.morphoMarketsData[m.value] = yield (0, morphoBlue_1._getMorphoBluePortfolioMarketData)(client, network, m, blockNumber); })),
153
+ ...morphoMidnightMarkets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.morphoMidnightMarketsData[m.value] = yield (0, morphoMidnight_1._getMorphoMidnightMarketData)(client, network, m, blockNumber); })),
154
+ ...compoundV3Markets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.compoundV3MarketsData[m.value] = yield (0, compoundV3_1._getCompoundV3MarketsData)(client, network, m, defaultClient, blockNumber, blockTimestamp); })),
155
+ ...sparkMarkets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.sparkMarketsData[m.value] = yield (0, spark_1._getSparkMarketsData)(client, network, m, blockNumber); })),
156
+ ...aaveV3Markets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.aaveV3MarketsData[m.value] = yield (0, aaveV3_1._getAaveV3MarketData)(client, network, m, blockNumber, blockTimestamp); })),
157
+ ...aaveV4Spokes.map((s) => __awaiter(this, void 0, void 0, function* () { markets.aaveV4SpokesData[s.value] = yield (0, aaveV4_1._getAaveV4SpokeData)(client, network, s, blockNumber, blockTimestamp); })),
158
+ ...aaveV2Markets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.aaveV2MarketsData[m.value] = yield (0, aaveV2_1._getAaveV2MarketsData)(client, network, m, blockNumber); })),
159
+ ...compoundV2Markets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.compoundV2MarketsData[m.value] = yield (0, compoundV2_1._getCompoundV2MarketsData)(client, network, blockNumber); })),
160
+ ...crvUsdMarkets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.crvUsdMarketsData[m.value] = yield (0, curveUsd_1._getCurveUsdGlobalData)(client, network, m, blockNumber); })),
161
+ ...llamaLendMarkets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.llamaLendMarketsData[m.value] = yield (0, llamaLend_1._getLlamaLendGlobalData)(client, network, m, blockNumber); })),
162
+ ...liquityV2Markets.map((m) => __awaiter(this, void 0, void 0, function* () { markets.liquityV2MarketsData[m.value] = yield (0, liquityV2_1._getLiquityV2MarketData)(client, network, m, blockNumber); })),
163
+ (() => __awaiter(this, void 0, void 0, function* () {
164
+ if (!fetchFluid || !fetchFluidMarkets)
165
+ return;
166
+ try {
167
+ markets.fluidMarketsData = yield (0, fluid_1._getAllFluidMarketDataPortfolio)(client, network, blockNumber, blockTimestamp);
168
+ }
169
+ catch (error) {
170
+ console.error('Error fetching Fluid markets data:', error);
171
+ }
172
+ }))(),
173
+ (() => __awaiter(this, void 0, void 0, function* () {
174
+ if (!fetchMaker)
175
+ return;
176
+ try {
177
+ markets.makerMarketsData = yield (0, maker_1._getMakerIlksData)(client, network, markets_1.MakerActiveIlks, blockNumber);
178
+ }
179
+ catch (error) {
180
+ console.error('Error fetching Maker ilks data:', error);
181
+ }
182
+ }))(),
183
+ ...addresses.map((address) => __awaiter(this, void 0, void 0, function* () {
184
+ if (!fetchMaker)
185
+ return;
186
+ makerCdps[lower(address)] = yield (0, maker_1._getUserCdps)(client, network, address, blockNumber);
187
+ })),
188
+ ...addresses.map((address) => fetchFluid && run(`Fluid positions for address ${address}`, () => (0, fluid_1._getUserPositionsPortfolio)(client, network, address, blockNumber), (userPositions) => {
189
+ for (const position of userPositions) {
190
+ if (position.userData && positive(position.userData.suppliedUsd))
191
+ positions[lower(address)].fluid.data[position.userData.nftId] = position.userData;
192
+ }
193
+ }, (err) => { positions[lower(address)].fluid = { error: err.error, data: {} }; })),
194
+ ...(fetchStaking ? [
195
+ ...addresses.map((address) => fetchFluid && run(`Fluid lend data for address ${address}`, () => (0, fluid_1._getAllUserEarnPositionsWithFTokens)(client, network, address, blockNumber), (data) => { stakingPositions[lower(address)].fluid = data; }, (err) => { stakingPositions[lower(address)].fluid = err; })),
196
+ ...addresses.map((address) => fetchLiquity && run(`Liquity staking data for address ${address}`, () => (0, liquity_1.getLiquityStakingData)(client, network, address, blockNumber), (data) => { stakingPositions[lower(address)].liquity = data; }, (err) => { stakingPositions[lower(address)].liquity = err; })),
197
+ ...addresses.map((address) => has(types_1.PortfolioProtocol.AaveV3) && isMainnet && run(`Aave V3 staking data for address ${address}`, () => (0, aaveV3_1.getStakeAaveData)(client, network, address, blockNumber), (data) => { stakingPositions[lower(address)].aaveV3 = data; }, (err) => { stakingPositions[lower(address)].aaveV3 = err; })),
198
+ ...addresses.map((address) => has(types_1.PortfolioProtocol.AaveV3) && isMainnet && run(`Umbrella staking data for address ${address}`, () => (0, umbrella_1.getUmbrellaData)(client, network, address, blockNumber), (data) => { stakingPositions[lower(address)].umbrella = data; }, (err) => { stakingPositions[lower(address)].umbrella = err; })),
199
+ ...perAddress(liquityV2StakingMarkets, (market, address) => run(`Liquity V2 staking data for address ${address}, market ${market.value}`, () => (0, liquityV2_1.getLiquityV2Staking)(client, network, market.value, address, blockNumber), (data) => { stakingPositions[lower(address)].liquityV2[market.value] = { error: '', data }; }, (err) => { stakingPositions[lower(address)].liquityV2[market.value] = err; })),
200
+ ] : []),
201
+ ...(fetchRewards ? [
202
+ batchRewards('king', 'King rewards data', () => (0, king_1.getKingRewards)(client, network, addresses, blockNumber), isMainnet),
203
+ batchRewards('uniswap', 'Uniswap rewards data', () => (0, uniswap_1.getUniswapRewards)(client, network, addresses, blockNumber), isMainnet),
204
+ batchRewards('spk', 'Spark Airdrop rewards data', () => (0, spark_2.fetchSparkAirdropRewards)(client, network, addresses, blockNumber), isMainnet && has(types_1.PortfolioProtocol.Spark)),
205
+ batchRewards('ethena', 'Ethena Airdrop rewards data', () => (0, ethena_1.fetchEthenaAirdropRewards)(addresses), isMainnet),
206
+ ...addresses.map((address) => run(`Merkl rewards data for address ${address}`, () => (0, aaveV3_2.getMerklUnclaimedRewards)(address, network), (data) => { rewardsData[lower(address)].merkl = { error: '', data }; }, (err) => { rewardsData[lower(address)].merkl = err; })),
207
+ ...perAddress(aaveV3Markets, (market, address) => run(`Aave V3 rewards data for address ${address}, market ${market.value}`, () => (0, aaveV3_2.getUnclaimedRewardsForAllMarkets)(client, network, address, market.providerAddress, blockNumber), (data) => { rewardsData[lower(address)].aaveV3[market.value] = { error: '', data }; }, (err) => { rewardsData[lower(address)].aaveV3[market.value] = err; })),
208
+ ...perAddress(sparkMarkets, (market, address) => {
209
+ if (!isMainnet) {
210
+ rewardsData[lower(address)].spark[market.value] = { error: '', data: [] };
211
+ return Promise.resolve();
212
+ }
213
+ return run(`Spark rewards data for address ${address}, market ${market.value}`, () => (0, spark_2.fetchSparkRewards)(client, network, address, market.providerAddress, blockNumber), (data) => { rewardsData[lower(address)].spark[market.value] = { error: '', data }; }, (err) => { rewardsData[lower(address)].spark[market.value] = err; });
214
+ }),
215
+ ] : []),
216
+ ]);
217
+ yield Promise.all([
218
+ ...perAddress(aaveV3Markets, (market, address) => run(`AaveV3 account data for address ${address} on market ${market.value}`, () => (0, aaveV3_1._getAaveV3AccountData)(client, network, address, Object.assign({ selectedMarket: market }, markets.aaveV3MarketsData[market.value]), blockNumber), (data) => { if (returnEmptyEModePositions || positive(data.suppliedUsd))
219
+ positions[lower(address)].aaveV3[market.value] = { error: '', data }; }, (err) => { positions[lower(address)].aaveV3[market.value] = err; })),
220
+ ...perAddress(sparkMarkets, (market, address) => run(`Spark account data for address ${address} on market ${market.value}`, () => (0, spark_1._getSparkAccountData)(client, network, address, { selectedMarket: market, assetsData: markets.sparkMarketsData[market.value].assetsData, eModeCategoriesData: markets.sparkMarketsData[market.value].eModeCategoriesData }, blockNumber), (data) => { if (returnEmptyEModePositions || positive(data.suppliedUsd))
221
+ positions[lower(address)].spark[market.value] = { error: '', data }; }, (err) => { positions[lower(address)].spark[market.value] = err; })),
222
+ ...perAddress(aaveV4Spokes, (spoke, address) => run(`AaveV4 account data for address ${address} on spoke ${spoke.value}`, () => (0, aaveV4_1._getAaveV4AccountData)(client, network, markets.aaveV4SpokesData[spoke.value], address, blockNumber), (data) => { if (positive(data.suppliedUsd))
223
+ positions[lower(address)].aaveV4[spoke.value] = { error: '', data }; }, (err) => { positions[lower(address)].aaveV4[spoke.value] = err; })),
224
+ ...perAddress(morphoMarkets, (market, address) => run(`MorphoBlue account data for address ${address} on market ${market.value}`, () => (0, morphoBlue_1._getMorphoBlueAccountData)(client, network, address, market, markets.morphoMarketsData[market.value], blockNumber), (data) => { if (positive(data.suppliedUsd))
225
+ positions[lower(address)].morphoBlue[market.value] = { error: '', data }; }, (err) => { positions[lower(address)].morphoBlue[market.value] = err; })),
226
+ ...(fetchStaking ? perAddress(morphoMarkets, (market, address) => run(`MorphoBlue earn data for address ${address} on market ${market.value}`, () => (0, morphoBlue_1.getMorphoEarn)(client, network, address, market, markets.morphoMarketsData[market.value], blockNumber), (data) => { if (data && positive(data.amount))
227
+ stakingPositions[lower(address)].morphoBlue[market.value] = { error: '', data }; }, (err) => { stakingPositions[lower(address)].morphoBlue[market.value] = err; })) : []),
228
+ ...perAddress(morphoMidnightMarkets, (market, address) => {
229
+ var _a;
230
+ if (!((_a = markets.morphoMidnightMarketsData[market.value]) === null || _a === void 0 ? void 0 : _a.isCreated))
231
+ return Promise.resolve();
232
+ return run(`MorphoMidnight account data for address ${address} on market ${market.value}`, () => (0, morphoMidnight_1._getMorphoMidnightAccountData)(client, network, address, market, markets.morphoMidnightMarketsData[market.value], blockNumber), (data) => { if (positive(data.suppliedUsd))
233
+ positions[lower(address)].morphoMidnight[market.value] = { error: '', data }; }, (err) => { positions[lower(address)].morphoMidnight[market.value] = err; });
234
+ }),
235
+ ...perAddress(compoundV3Markets, (market, address) => run(`CompoundV3 account data for address ${address} on market ${market.value}`, () => (0, compoundV3_1._getCompoundV3AccountData)(client, network, address, constants_1.ZERO_ADDRESS, { selectedMarket: market, assetsData: markets.compoundV3MarketsData[market.value].assetsData }, blockNumber), (data) => { if (positive(data.suppliedUsd))
236
+ positions[lower(address)].compoundV3[market.value] = { error: '', data }; }, (err) => { positions[lower(address)].compoundV3[market.value] = err; })),
237
+ ...perAddress(compoundV2Markets, (market, address) => run(`CompoundV2 account data for address ${address}`, () => (0, compoundV2_1._getCompoundV2AccountData)(client, network, address, markets.compoundV2MarketsData[market.value].assetsData, blockNumber), (data) => { if (positive(data.suppliedUsd))
238
+ positions[lower(address)].compoundV2[market.value] = { error: '', data }; }, (err) => { positions[lower(address)].compoundV2[market.value] = err; })),
239
+ ...perAddress(aaveV2Markets, (market, address) => run(`AaveV2 account data for address ${address}`, () => (0, aaveV2_1._getAaveV2AccountData)(client, network, address, markets.aaveV2MarketsData[market.value].assetsData, market, blockNumber), (data) => { if (positive(data.suppliedUsd))
240
+ positions[lower(address)].aaveV2[market.value] = { error: '', data }; }, (err) => { positions[lower(address)].aaveV2[market.value] = err; })),
241
+ ...perAddress(crvUsdMarkets, (market, address) => run(`Curve USD account data for address ${address} on market ${market.value}`, () => (0, curveUsd_1._getCurveUsdUserData)(client, network, address, market, markets.crvUsdMarketsData[market.value].activeBand, markets.crvUsdMarketsData[market.value].borrowRate, blockNumber), (data) => { if (positive(data.suppliedUsd) || positive(data.borrowedUsd))
242
+ positions[lower(address)].crvUsd[market.value] = { error: '', data }; }, (err) => { positions[lower(address)].crvUsd[market.value] = err; })),
243
+ ...perAddress(llamaLendMarkets, (market, address) => run(`LlamaLend account data for address ${address} on market ${market.value}`, () => (0, llamaLend_1._getLlamaLendUserData)(client, network, address, market, markets.llamaLendMarketsData[market.value], blockNumber), (data) => {
244
+ if (positive(data.suppliedUsd) || positive(data.borrowedUsd)) {
245
+ positions[lower(address)].llamaLend[market.value] = { error: '', data: Object.assign(Object.assign({}, data), { borrowRate: markets.llamaLendMarketsData[market.value].borrowRate }) };
246
+ }
247
+ }, (err) => { positions[lower(address)].llamaLend[market.value] = err; })),
248
+ ...addresses.map((address) => (makerCdps[lower(address)] || []).map((cdpInfo) => run(`Maker CDP data for address ${address} with ID ${cdpInfo.id}`, () => (0, maker_1._getMakerCdpData)(client, network, cdpInfo, markets.makerMarketsData[cdpInfo.ilkLabel], blockNumber), (data) => { if (data)
249
+ positions[lower(address)].maker[cdpInfo.id] = { error: '', data }; }, (err) => { positions[lower(address)].maker[cdpInfo.id] = err; }))).flat(),
250
+ ...addresses.map((address) => fetchLiquity && run(`Liquity trove info for address ${address}`, () => (0, liquity_1._getLiquityTroveInfo)(client, network, address, blockNumber), (data) => { if (positive(data.collateral))
251
+ positions[lower(address)].liquity = { error: '', data }; }, (err) => { positions[lower(address)].liquity = err; })),
252
+ ...(fetchStaking && has(types_1.PortfolioProtocol.LiquityV2) ? addresses.map((address) => {
253
+ if (!isMainnet) {
254
+ stakingPositions[lower(address)].liquityV2SBoldYBold = { error: '', data: null };
255
+ return Promise.resolve();
256
+ }
257
+ return run(`sBold/yBold data for address ${address}`, () => (0, liquityV2_1.getLiquitySAndYBold)(client, network, stakingPositions[lower(address)].liquityV2, address, blockNumber), (data) => { stakingPositions[lower(address)].liquityV2SBoldYBold = { error: '', data }; }, (err) => { stakingPositions[lower(address)].liquityV2SBoldYBold = err; });
258
+ }) : []),
259
+ ]);
260
+ return {
261
+ positions,
262
+ stakingPositions,
263
+ rewardsData,
264
+ markets,
265
+ };
266
+ });
267
+ }
@@ -19,4 +19,5 @@ export declare function getShifterPortfolioData(provider: EthereumProvider, netw
19
19
  markets: ShifterPortfolioMarketsData;
20
20
  }>;
21
21
  export * from './discovery';
22
+ export * from './customDeFiData';
22
23
  export { getWalletLendingSummaries } from './lendingSummaries';
@@ -825,5 +825,6 @@ function getShifterPortfolioData(provider_1, network_1, defaultProvider_1, addre
825
825
  });
826
826
  }
827
827
  __exportStar(require("./discovery"), exports);
828
+ __exportStar(require("./customDeFiData"), exports);
828
829
  var lendingSummaries_1 = require("./lendingSummaries");
829
830
  Object.defineProperty(exports, "getWalletLendingSummaries", { enumerable: true, get: function () { return lendingSummaries_1.getWalletLendingSummaries; } });
@@ -1,6 +1,50 @@
1
- import { MerklOpportunity } from '../types';
1
+ import { MerklCampaignListItem, MerklOpportunity } from '../types';
2
2
  /**
3
- * Fetches every page matching the query. Merkl returns 20 opportunities by default, so omitting
3
+ * Fetches every opportunity matching the query. Merkl returns 20 opportunities by default, so omitting
4
4
  * `items` and advancing `page` avoids imposing a client-side maximum on the result set.
5
5
  */
6
6
  export declare const fetchAllMerklOpportunities: (query: Record<string, string>) => Promise<MerklOpportunity[]>;
7
+ /** Fetches every campaign matching the query, e.g. `{ mainProtocolId: 'aave', status: 'LIVE,PAST' }`. */
8
+ export declare const fetchAllMerklCampaigns: (query: Record<string, string>) => Promise<MerklCampaignListItem[]>;
9
+ /**
10
+ * Fetches the opportunities with the given Merkl-internal ids, regardless of their current status.
11
+ * Ids Merkl no longer serves (hidden or test campaigns) are simply absent from the result.
12
+ */
13
+ export declare const fetchMerklOpportunitiesByIds: (ids: string[]) => Promise<MerklOpportunity[]>;
14
+ /**
15
+ * Returns the reward APR Merkl recorded for the opportunity at the given unix timestamp (seconds),
16
+ * or `undefined` when no campaign was computing for it then. Records are buckets keyed by their
17
+ * start, newest first, and each carries the last value recorded in the bucket. The hourly bucket of
18
+ * the timestamp's hour is used when Merkl still has it — it keeps hourly history for roughly the
19
+ * last ten weeks — and the daily bucket of the timestamp's day otherwise. Either window is a day
20
+ * wide to tolerate computation gaps and aligned to the bucket, so every block within one hour asks
21
+ * for (and caches) the same records.
22
+ */
23
+ export declare const fetchMerklOpportunityAprAt: (opportunityId: string, timestamp: number) => Promise<number | undefined>;
24
+ /** Drops every cached historical response (campaign lists, opportunities, APR buckets). */
25
+ export declare const clearMerklHistoryCache: () => void;
26
+ /**
27
+ * Reconstructs the opportunities that were live at `timestamp` (unix seconds), shaped like the
28
+ * live listing so the per-protocol reward mappers can consume either without knowing which they got:
29
+ * 1. every LIVE or PAST campaign for the protocol (and chain, when the query names one) is listed
30
+ * once per cache period — the list is block-independent, the exact window check happens here —
31
+ * and the ones whose [start, end] covers the timestamp identify the opportunities rewarded
32
+ * then (the live listing can't: campaigns live then are mostly PAST now and ones live now
33
+ * didn't exist then);
34
+ * 2. those opportunities are loaded by id (works for PAST ones too) and narrowed to `query.type`
35
+ * and `isRelevant`, so no APR history is fetched for opportunities the caller would discard;
36
+ * 3. each one's `apr` is replaced with the value Merkl recorded at the timestamp, and ones with no
37
+ * record then are dropped, since nothing was being computed for them.
38
+ * `status` is forced to LIVE so status filters downstream keep working, `campaigns` carries the
39
+ * covering campaigns, and a reward token breakdown is synthesized from the campaign's reward token
40
+ * when Merkl no longer serves one for the opportunity (it drops them once an opportunity is PAST).
41
+ * `query.status` is ignored: it describes the present, not the requested moment.
42
+ */
43
+ export declare const fetchMerklOpportunitiesAt: (query: Record<string, string>, timestamp: number, isRelevant?: (opportunity: MerklOpportunity) => boolean) => Promise<MerklOpportunity[]>;
44
+ /**
45
+ * Live opportunities when no timestamp is given, otherwise the opportunities as they were at that
46
+ * unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`. `isRelevant` only applies to the
47
+ * historical path, where it saves fetching APR history for opportunities the caller would discard;
48
+ * callers still filter the live listing themselves.
49
+ */
50
+ export declare const fetchMerklOpportunities: (query: Record<string, string>, asOfTimestamp?: number, isRelevant?: (opportunity: MerklOpportunity) => boolean) => Promise<MerklOpportunity[]>;
@@ -8,32 +8,203 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
11
14
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.fetchAllMerklOpportunities = void 0;
15
+ exports.fetchMerklOpportunities = exports.fetchMerklOpportunitiesAt = exports.clearMerklHistoryCache = exports.fetchMerklOpportunityAprAt = exports.fetchMerklOpportunitiesByIds = exports.fetchAllMerklCampaigns = exports.fetchAllMerklOpportunities = void 0;
16
+ const memoizee_1 = __importDefault(require("memoizee"));
17
+ const types_1 = require("../types");
13
18
  const utils_1 = require("./utils");
14
- const MERKL_OPPORTUNITIES_URL = 'https://fe.defisaver.com/api/merkl/opportunities';
19
+ const MERKL_API_URL = 'https://fe.defisaver.com/api/merkl';
20
+ const MERKL_OPPORTUNITIES_URL = `${MERKL_API_URL}/opportunities`;
21
+ const MERKL_CAMPAIGNS_URL = `${MERKL_API_URL}/campaigns`;
22
+ // Merkl caps list pages at 100 items; opportunity ids are batched below that so a single page
23
+ // covers every id in the batch.
24
+ const MERKL_MAX_PAGE_ITEMS = 100;
25
+ const OPPORTUNITY_ID_BATCH_SIZE = 50;
26
+ // APR history is fetched per opportunity, so historical lookups are throttled to keep a block with
27
+ // many live campaigns from firing every request at once.
28
+ const APR_RECORDS_CONCURRENCY = 10;
29
+ const SECONDS_PER_HOUR = 60 * 60;
30
+ const SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;
31
+ // Historical lookups describe the past, so their responses are reused for a while: a job that
32
+ // walks many blocks (or fetches several protocols/chains at one block in parallel) would otherwise
33
+ // re-request the same campaign lists, opportunities and APR buckets for every block.
34
+ const HISTORY_CACHE_TTL = 5 * 60 * 1000;
35
+ const merklGet = (url, query, label) => __awaiter(void 0, void 0, void 0, function* () {
36
+ const res = yield fetch(`${url}?${new URLSearchParams(query)}`, { signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT) });
37
+ if (!res.ok) {
38
+ const body = yield res.text().catch(() => '');
39
+ throw new Error(`Failed to fetch Merkl ${label} (HTTP ${res.status}${body ? `: ${body.slice(0, 200)}` : ''})`);
40
+ }
41
+ return res.json();
42
+ });
15
43
  /**
16
- * Fetches every page matching the query. Merkl returns 20 opportunities by default, so omitting
17
- * `items` and advancing `page` avoids imposing a client-side maximum on the result set.
44
+ * Fetches every page matching the query, advancing `page` until an empty page comes back. When
45
+ * `items` is omitted, Merkl's default page size applies and no client-side maximum is imposed.
18
46
  */
19
- const fetchAllMerklOpportunities = (query) => __awaiter(void 0, void 0, void 0, function* () {
20
- const opportunities = [];
47
+ const fetchAllMerklPages = (url, query, label, items) => __awaiter(void 0, void 0, void 0, function* () {
48
+ const results = [];
21
49
  let page = 0;
22
- let pageOpportunities;
50
+ let pageResults;
23
51
  do {
24
- const searchParams = new URLSearchParams(Object.assign(Object.assign({}, query), { page: page.toString() }));
25
- const res = yield fetch(`${MERKL_OPPORTUNITIES_URL}?${searchParams}`, {
26
- signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT),
27
- });
28
- if (!res.ok)
29
- throw new Error(`Failed to fetch Merkl opportunities page ${page}`);
30
- const data = yield res.json(); // eslint-disable-line no-await-in-loop
52
+ const pageQuery = Object.assign(Object.assign(Object.assign({}, query), { page: page.toString() }), (items ? { items: items.toString() } : {}));
53
+ const data = yield merklGet(url, pageQuery, `${label} page ${page}`); // eslint-disable-line no-await-in-loop
31
54
  if (!Array.isArray(data))
32
- throw new Error(`Invalid Merkl opportunities response on page ${page}`);
33
- pageOpportunities = data;
34
- opportunities.push(...pageOpportunities);
55
+ throw new Error(`Invalid Merkl ${label} response on page ${page}`);
56
+ pageResults = data;
57
+ results.push(...pageResults);
35
58
  page += 1;
36
- } while (pageOpportunities.length > 0);
37
- return opportunities;
59
+ } while (pageResults.length > 0);
60
+ return results;
61
+ });
62
+ /**
63
+ * Fetches every opportunity matching the query. Merkl returns 20 opportunities by default, so omitting
64
+ * `items` and advancing `page` avoids imposing a client-side maximum on the result set.
65
+ */
66
+ const fetchAllMerklOpportunities = (query) => __awaiter(void 0, void 0, void 0, function* () {
67
+ return (fetchAllMerklPages(MERKL_OPPORTUNITIES_URL, query, 'opportunities'));
38
68
  });
39
69
  exports.fetchAllMerklOpportunities = fetchAllMerklOpportunities;
70
+ /** Fetches every campaign matching the query, e.g. `{ mainProtocolId: 'aave', status: 'LIVE,PAST' }`. */
71
+ const fetchAllMerklCampaigns = (query) => __awaiter(void 0, void 0, void 0, function* () {
72
+ return (fetchAllMerklPages(MERKL_CAMPAIGNS_URL, query, 'campaigns', MERKL_MAX_PAGE_ITEMS));
73
+ });
74
+ exports.fetchAllMerklCampaigns = fetchAllMerklCampaigns;
75
+ const fetchAllMerklCampaignsCached = (0, memoizee_1.default)(exports.fetchAllMerklCampaigns, {
76
+ promise: true,
77
+ maxAge: HISTORY_CACHE_TTL,
78
+ normalizer: ([query]) => JSON.stringify(Object.entries(query).sort()),
79
+ });
80
+ /**
81
+ * Fetches the opportunities with the given Merkl-internal ids, regardless of their current status.
82
+ * Ids Merkl no longer serves (hidden or test campaigns) are simply absent from the result.
83
+ */
84
+ const fetchMerklOpportunitiesByIds = (ids) => __awaiter(void 0, void 0, void 0, function* () {
85
+ const batches = [];
86
+ for (let i = 0; i < ids.length; i += OPPORTUNITY_ID_BATCH_SIZE)
87
+ batches.push(ids.slice(i, i + OPPORTUNITY_ID_BATCH_SIZE));
88
+ const results = yield Promise.all(batches.map((batch) => merklGet(MERKL_OPPORTUNITIES_URL, { id: batch.join(','), items: MERKL_MAX_PAGE_ITEMS.toString() }, 'opportunities by id')));
89
+ return results.flatMap((data) => {
90
+ if (!Array.isArray(data))
91
+ throw new Error('Invalid Merkl opportunities by id response');
92
+ return data;
93
+ });
94
+ });
95
+ exports.fetchMerklOpportunitiesByIds = fetchMerklOpportunitiesByIds;
96
+ const fetchMerklOpportunitiesByIdsCached = (0, memoizee_1.default)(exports.fetchMerklOpportunitiesByIds, {
97
+ promise: true,
98
+ maxAge: HISTORY_CACHE_TTL,
99
+ normalizer: ([ids]) => [...ids].sort().join(','),
100
+ });
101
+ const fetchLatestMerklAprRecord = (opportunityId, grain, to) => __awaiter(void 0, void 0, void 0, function* () {
102
+ const records = yield merklGet(`${MERKL_OPPORTUNITIES_URL}/${opportunityId}/apr-records`, {
103
+ grain,
104
+ from: (to - SECONDS_PER_DAY).toString(),
105
+ to: to.toString(),
106
+ items: '1',
107
+ }, `APR records for opportunity ${opportunityId}`);
108
+ if (!Array.isArray(records))
109
+ throw new Error(`Invalid Merkl APR records response for opportunity ${opportunityId}`);
110
+ return records[0];
111
+ });
112
+ /**
113
+ * Returns the reward APR Merkl recorded for the opportunity at the given unix timestamp (seconds),
114
+ * or `undefined` when no campaign was computing for it then. Records are buckets keyed by their
115
+ * start, newest first, and each carries the last value recorded in the bucket. The hourly bucket of
116
+ * the timestamp's hour is used when Merkl still has it — it keeps hourly history for roughly the
117
+ * last ten weeks — and the daily bucket of the timestamp's day otherwise. Either window is a day
118
+ * wide to tolerate computation gaps and aligned to the bucket, so every block within one hour asks
119
+ * for (and caches) the same records.
120
+ */
121
+ const fetchMerklOpportunityAprAt = (opportunityId, timestamp) => __awaiter(void 0, void 0, void 0, function* () {
122
+ var _a;
123
+ const hour = Math.floor(timestamp / SECONDS_PER_HOUR) * SECONDS_PER_HOUR;
124
+ const hourly = yield fetchLatestMerklAprRecord(opportunityId, 'HOUR', hour);
125
+ if (hourly)
126
+ return hourly.apr;
127
+ const day = Math.floor(timestamp / SECONDS_PER_DAY) * SECONDS_PER_DAY;
128
+ return (_a = (yield fetchLatestMerklAprRecord(opportunityId, 'DAY', day))) === null || _a === void 0 ? void 0 : _a.apr;
129
+ });
130
+ exports.fetchMerklOpportunityAprAt = fetchMerklOpportunityAprAt;
131
+ const fetchMerklOpportunityAprAtCached = (0, memoizee_1.default)(exports.fetchMerklOpportunityAprAt, {
132
+ promise: true,
133
+ maxAge: HISTORY_CACHE_TTL,
134
+ normalizer: ([opportunityId, timestamp]) => `${opportunityId}:${Math.floor(timestamp / SECONDS_PER_HOUR)}`,
135
+ });
136
+ /** Drops every cached historical response (campaign lists, opportunities, APR buckets). */
137
+ const clearMerklHistoryCache = () => {
138
+ fetchAllMerklCampaignsCached.clear();
139
+ fetchMerklOpportunitiesByIdsCached.clear();
140
+ fetchMerklOpportunityAprAtCached.clear();
141
+ };
142
+ exports.clearMerklHistoryCache = clearMerklHistoryCache;
143
+ const mapWithConcurrency = (items, concurrency, fn) => __awaiter(void 0, void 0, void 0, function* () {
144
+ const results = [];
145
+ for (let i = 0; i < items.length; i += concurrency) {
146
+ results.push(...yield Promise.all(items.slice(i, i + concurrency).map(fn))); // eslint-disable-line no-await-in-loop
147
+ }
148
+ return results;
149
+ });
150
+ /**
151
+ * Reconstructs the opportunities that were live at `timestamp` (unix seconds), shaped like the
152
+ * live listing so the per-protocol reward mappers can consume either without knowing which they got:
153
+ * 1. every LIVE or PAST campaign for the protocol (and chain, when the query names one) is listed
154
+ * once per cache period — the list is block-independent, the exact window check happens here —
155
+ * and the ones whose [start, end] covers the timestamp identify the opportunities rewarded
156
+ * then (the live listing can't: campaigns live then are mostly PAST now and ones live now
157
+ * didn't exist then);
158
+ * 2. those opportunities are loaded by id (works for PAST ones too) and narrowed to `query.type`
159
+ * and `isRelevant`, so no APR history is fetched for opportunities the caller would discard;
160
+ * 3. each one's `apr` is replaced with the value Merkl recorded at the timestamp, and ones with no
161
+ * record then are dropped, since nothing was being computed for them.
162
+ * `status` is forced to LIVE so status filters downstream keep working, `campaigns` carries the
163
+ * covering campaigns, and a reward token breakdown is synthesized from the campaign's reward token
164
+ * when Merkl no longer serves one for the opportunity (it drops them once an opportunity is PAST).
165
+ * `query.status` is ignored: it describes the present, not the requested moment.
166
+ */
167
+ const fetchMerklOpportunitiesAt = (query_1, timestamp_1, ...args_1) => __awaiter(void 0, [query_1, timestamp_1, ...args_1], void 0, function* (query, timestamp, isRelevant = () => true) {
168
+ var _a;
169
+ const campaignQuery = { status: 'LIVE,PAST' };
170
+ if (query.mainProtocolId)
171
+ campaignQuery.mainProtocolId = query.mainProtocolId;
172
+ if (query.chainId)
173
+ campaignQuery.chainId = query.chainId;
174
+ const campaigns = (yield fetchAllMerklCampaignsCached(campaignQuery))
175
+ .filter((c) => { var _a, _b; return c.opportunityId && +((_a = c.startTimestamp) !== null && _a !== void 0 ? _a : 0) <= timestamp && timestamp <= +((_b = c.endTimestamp) !== null && _b !== void 0 ? _b : 0); });
176
+ const campaignsByOpportunity = {};
177
+ campaigns.forEach((c) => {
178
+ if (!campaignsByOpportunity[c.opportunityId])
179
+ campaignsByOpportunity[c.opportunityId] = [];
180
+ campaignsByOpportunity[c.opportunityId].push(c);
181
+ });
182
+ const opportunityIds = Object.keys(campaignsByOpportunity);
183
+ if (!opportunityIds.length)
184
+ return [];
185
+ const types = (_a = query.type) === null || _a === void 0 ? void 0 : _a.split(',').filter(Boolean);
186
+ const opportunities = (yield fetchMerklOpportunitiesByIdsCached(opportunityIds))
187
+ .filter((o) => (!(types === null || types === void 0 ? void 0 : types.length) || types.includes(o.type)) && isRelevant(o));
188
+ const aprs = yield mapWithConcurrency(opportunities, APR_RECORDS_CONCURRENCY, (o) => fetchMerklOpportunityAprAtCached(o.id, timestamp));
189
+ return opportunities.flatMap((o, i) => {
190
+ var _a, _b, _c;
191
+ const apr = aprs[i];
192
+ if (apr === undefined)
193
+ return [];
194
+ const coveringCampaigns = campaignsByOpportunity[o.id];
195
+ const rewardToken = (_a = coveringCampaigns.find((c) => c.rewardToken)) === null || _a === void 0 ? void 0 : _a.rewardToken;
196
+ const hasBreakdown = !!((_c = (_b = o.rewardsRecord) === null || _b === void 0 ? void 0 : _b.breakdowns) === null || _c === void 0 ? void 0 : _c.length);
197
+ return [Object.assign(Object.assign({}, o), { status: types_1.OpportunityStatus.LIVE, apr, campaigns: coveringCampaigns, rewardsRecord: hasBreakdown || !rewardToken ? o.rewardsRecord : Object.assign(Object.assign({}, o.rewardsRecord), { breakdowns: [{ token: rewardToken, campaignId: coveringCampaigns[0].campaignId }] }) })];
198
+ });
199
+ });
200
+ exports.fetchMerklOpportunitiesAt = fetchMerklOpportunitiesAt;
201
+ /**
202
+ * Live opportunities when no timestamp is given, otherwise the opportunities as they were at that
203
+ * unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`. `isRelevant` only applies to the
204
+ * historical path, where it saves fetching APR history for opportunities the caller would discard;
205
+ * callers still filter the live listing themselves.
206
+ */
207
+ const fetchMerklOpportunities = (query, asOfTimestamp, isRelevant) => __awaiter(void 0, void 0, void 0, function* () {
208
+ return (asOfTimestamp === undefined ? (0, exports.fetchAllMerklOpportunities)(query) : (0, exports.fetchMerklOpportunitiesAt)(query, asOfTimestamp, isRelevant));
209
+ });
210
+ exports.fetchMerklOpportunities = fetchMerklOpportunities;
@@ -1,14 +1,14 @@
1
1
  import Dec from 'decimal.js';
2
2
  import { Client, PublicClient } from 'viem';
3
- import { EthAddress, NetworkNumber } from '../types/common';
4
- export declare const getEthPrice: (client: Client) => Promise<string>;
5
- export declare const getUSDCPrice: (client: Client) => Promise<string>;
6
- export declare const getCompPrice: (client: Client) => Promise<string>;
7
- export declare const getWstETHPrice: (client: Client, network?: NetworkNumber) => Promise<string>;
8
- export declare const getWeETHPrice: (client: Client, network?: NetworkNumber) => Promise<string>;
9
- export declare const getWsrETHPrice: (client: Client, network?: NetworkNumber) => Promise<string>;
10
- export declare const getSyrupUSDTPrice: (client: Client, network?: NetworkNumber) => Promise<string>;
11
- export declare const getWstUSRPrice: (client: Client, network?: NetworkNumber) => Promise<string>;
3
+ import { Blockish, EthAddress, NetworkNumber } from '../types/common';
4
+ export declare const getEthPrice: (client: Client, block?: Blockish) => Promise<string>;
5
+ export declare const getUSDCPrice: (client: Client, block?: Blockish) => Promise<string>;
6
+ export declare const getCompPrice: (client: Client, block?: Blockish) => Promise<string>;
7
+ export declare const getWstETHPrice: (client: Client, network?: NetworkNumber, block?: Blockish) => Promise<string>;
8
+ export declare const getWeETHPrice: (client: Client, network?: NetworkNumber, block?: Blockish) => Promise<string>;
9
+ export declare const getWsrETHPrice: (client: Client, network?: NetworkNumber, block?: Blockish) => Promise<string>;
10
+ export declare const getSyrupUSDTPrice: (client: Client, network?: NetworkNumber, block?: Blockish) => Promise<string>;
11
+ export declare const getWstUSRPrice: (client: Client, network?: NetworkNumber, block?: Blockish) => Promise<string>;
12
12
  export declare const getWstETHChainLinkPriceCalls: (client: PublicClient, network: NetworkNumber) => ({
13
13
  address: `0x${string}`;
14
14
  abi: readonly [{
@@ -1821,7 +1821,7 @@ export declare const parseWeETHPriceCalls: (_ethPrice: string, weETHrateAnswer:
1821
1821
  ethPrice: Dec;
1822
1822
  weETHRate: string;
1823
1823
  };
1824
- export declare const getWstETHPriceFluid: (client: PublicClient, network: NetworkNumber) => Promise<string>;
1825
- export declare const getBTCPriceForFluid: (client: PublicClient, network: NetworkNumber) => Promise<string>;
1826
- export declare const getEthPriceForFluid: (client: PublicClient, network: NetworkNumber) => Promise<string>;
1824
+ export declare const getWstETHPriceFluid: (client: PublicClient, network: NetworkNumber, block?: Blockish) => Promise<string>;
1825
+ export declare const getBTCPriceForFluid: (client: PublicClient, network: NetworkNumber, block?: Blockish) => Promise<string>;
1826
+ export declare const getEthPriceForFluid: (client: PublicClient, network: NetworkNumber, block?: Blockish) => Promise<string>;
1827
1827
  export declare const getChainlinkAssetAddress: (symbol: string, network: NetworkNumber) => EthAddress;