@defisaver/positions-sdk 2.1.169-custom-fetching-3-dev → 2.1.169-custom-fetching-5-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/aaveV3/merkl.js +1 -1
- package/cjs/services/merkl.d.ts +20 -10
- package/cjs/services/merkl.js +78 -30
- package/esm/aaveV3/merkl.js +1 -1
- package/esm/services/merkl.d.ts +20 -10
- package/esm/services/merkl.js +73 -29
- package/package.json +1 -1
- package/src/aaveV3/merkl.ts +1 -1
- package/src/services/merkl.ts +84 -27
package/cjs/aaveV3/merkl.js
CHANGED
|
@@ -49,7 +49,7 @@ const getMerkleCampaigns = (chainId, asOfTimestamp) => __awaiter(void 0, void 0,
|
|
|
49
49
|
mainProtocolId: 'aave',
|
|
50
50
|
chainId: chainId.toString(),
|
|
51
51
|
status: types_1.OpportunityStatus.LIVE,
|
|
52
|
-
}, asOfTimestamp);
|
|
52
|
+
}, asOfTimestamp, (o) => { var _a; return !((_a = o.type) === null || _a === void 0 ? void 0 : _a.startsWith('AAVE_V4_')); });
|
|
53
53
|
const relevantOpportunities = opportunities
|
|
54
54
|
.filter((o) => o.chainId === chainId)
|
|
55
55
|
.filter((o) => o.status === types_1.OpportunityStatus.LIVE);
|
package/cjs/services/merkl.d.ts
CHANGED
|
@@ -13,18 +13,26 @@ export declare const fetchAllMerklCampaigns: (query: Record<string, string>) =>
|
|
|
13
13
|
export declare const fetchMerklOpportunitiesByIds: (ids: string[]) => Promise<MerklOpportunity[]>;
|
|
14
14
|
/**
|
|
15
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
|
|
17
|
-
*
|
|
18
|
-
*
|
|
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.
|
|
19
22
|
*/
|
|
20
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;
|
|
21
26
|
/**
|
|
22
27
|
* Reconstructs the opportunities that were live at `timestamp` (unix seconds), shaped like the
|
|
23
28
|
* live listing so the per-protocol reward mappers can consume either without knowing which they got:
|
|
24
|
-
* 1.
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
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;
|
|
28
36
|
* 3. each one's `apr` is replaced with the value Merkl recorded at the timestamp, and ones with no
|
|
29
37
|
* record then are dropped, since nothing was being computed for them.
|
|
30
38
|
* `status` is forced to LIVE so status filters downstream keep working, `campaigns` carries the
|
|
@@ -32,9 +40,11 @@ export declare const fetchMerklOpportunityAprAt: (opportunityId: string, timesta
|
|
|
32
40
|
* when Merkl no longer serves one for the opportunity (it drops them once an opportunity is PAST).
|
|
33
41
|
* `query.status` is ignored: it describes the present, not the requested moment.
|
|
34
42
|
*/
|
|
35
|
-
export declare const fetchMerklOpportunitiesAt: (query: Record<string, string>, timestamp: number) => Promise<MerklOpportunity[]>;
|
|
43
|
+
export declare const fetchMerklOpportunitiesAt: (query: Record<string, string>, timestamp: number, isRelevant?: (opportunity: MerklOpportunity) => boolean) => Promise<MerklOpportunity[]>;
|
|
36
44
|
/**
|
|
37
45
|
* Live opportunities when no timestamp is given, otherwise the opportunities as they were at that
|
|
38
|
-
* unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`.
|
|
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.
|
|
39
49
|
*/
|
|
40
|
-
export declare const fetchMerklOpportunities: (query: Record<string, string>, asOfTimestamp?: number) => Promise<MerklOpportunity[]>;
|
|
50
|
+
export declare const fetchMerklOpportunities: (query: Record<string, string>, asOfTimestamp?: number, isRelevant?: (opportunity: MerklOpportunity) => boolean) => Promise<MerklOpportunity[]>;
|
package/cjs/services/merkl.js
CHANGED
|
@@ -8,8 +8,12 @@ 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.fetchMerklOpportunities = exports.fetchMerklOpportunitiesAt = exports.fetchMerklOpportunityAprAt = exports.fetchMerklOpportunitiesByIds = exports.fetchAllMerklCampaigns = 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"));
|
|
13
17
|
const types_1 = require("../types");
|
|
14
18
|
const utils_1 = require("./utils");
|
|
15
19
|
const MERKL_API_URL = 'https://fe.defisaver.com/api/merkl';
|
|
@@ -22,11 +26,18 @@ const OPPORTUNITY_ID_BATCH_SIZE = 50;
|
|
|
22
26
|
// APR history is fetched per opportunity, so historical lookups are throttled to keep a block with
|
|
23
27
|
// many live campaigns from firing every request at once.
|
|
24
28
|
const APR_RECORDS_CONCURRENCY = 10;
|
|
25
|
-
const
|
|
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;
|
|
26
35
|
const merklGet = (url, query, label) => __awaiter(void 0, void 0, void 0, function* () {
|
|
27
36
|
const res = yield fetch(`${url}?${new URLSearchParams(query)}`, { signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT) });
|
|
28
|
-
if (!res.ok)
|
|
29
|
-
|
|
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
|
+
}
|
|
30
41
|
return res.json();
|
|
31
42
|
});
|
|
32
43
|
/**
|
|
@@ -61,6 +72,11 @@ const fetchAllMerklCampaigns = (query) => __awaiter(void 0, void 0, void 0, func
|
|
|
61
72
|
return (fetchAllMerklPages(MERKL_CAMPAIGNS_URL, query, 'campaigns', MERKL_MAX_PAGE_ITEMS));
|
|
62
73
|
});
|
|
63
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
|
+
});
|
|
64
80
|
/**
|
|
65
81
|
* Fetches the opportunities with the given Merkl-internal ids, regardless of their current status.
|
|
66
82
|
* Ids Merkl no longer serves (hidden or test campaigns) are simply absent from the result.
|
|
@@ -77,25 +93,53 @@ const fetchMerklOpportunitiesByIds = (ids) => __awaiter(void 0, void 0, void 0,
|
|
|
77
93
|
});
|
|
78
94
|
});
|
|
79
95
|
exports.fetchMerklOpportunitiesByIds = fetchMerklOpportunitiesByIds;
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
const fetchMerklOpportunityAprAt = (opportunityId, timestamp) => __awaiter(void 0, void 0, void 0, function* () {
|
|
87
|
-
var _a;
|
|
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* () {
|
|
88
102
|
const records = yield merklGet(`${MERKL_OPPORTUNITIES_URL}/${opportunityId}/apr-records`, {
|
|
89
|
-
grain
|
|
90
|
-
from: (
|
|
91
|
-
to:
|
|
103
|
+
grain,
|
|
104
|
+
from: (to - SECONDS_PER_DAY).toString(),
|
|
105
|
+
to: to.toString(),
|
|
92
106
|
items: '1',
|
|
93
107
|
}, `APR records for opportunity ${opportunityId}`);
|
|
94
108
|
if (!Array.isArray(records))
|
|
95
109
|
throw new Error(`Invalid Merkl APR records response for opportunity ${opportunityId}`);
|
|
96
|
-
return
|
|
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;
|
|
97
129
|
});
|
|
98
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;
|
|
99
143
|
const mapWithConcurrency = (items, concurrency, fn) => __awaiter(void 0, void 0, void 0, function* () {
|
|
100
144
|
const results = [];
|
|
101
145
|
for (let i = 0; i < items.length; i += concurrency) {
|
|
@@ -106,10 +150,13 @@ const mapWithConcurrency = (items, concurrency, fn) => __awaiter(void 0, void 0,
|
|
|
106
150
|
/**
|
|
107
151
|
* Reconstructs the opportunities that were live at `timestamp` (unix seconds), shaped like the
|
|
108
152
|
* live listing so the per-protocol reward mappers can consume either without knowing which they got:
|
|
109
|
-
* 1.
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
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;
|
|
113
160
|
* 3. each one's `apr` is replaced with the value Merkl recorded at the timestamp, and ones with no
|
|
114
161
|
* record then are dropped, since nothing was being computed for them.
|
|
115
162
|
* `status` is forced to LIVE so status filters downstream keep working, `campaigns` carries the
|
|
@@ -117,15 +164,14 @@ const mapWithConcurrency = (items, concurrency, fn) => __awaiter(void 0, void 0,
|
|
|
117
164
|
* when Merkl no longer serves one for the opportunity (it drops them once an opportunity is PAST).
|
|
118
165
|
* `query.status` is ignored: it describes the present, not the requested moment.
|
|
119
166
|
*/
|
|
120
|
-
const fetchMerklOpportunitiesAt = (
|
|
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) {
|
|
121
168
|
var _a;
|
|
122
|
-
const campaignQuery = { status: 'LIVE,PAST'
|
|
169
|
+
const campaignQuery = { status: 'LIVE,PAST' };
|
|
123
170
|
if (query.mainProtocolId)
|
|
124
171
|
campaignQuery.mainProtocolId = query.mainProtocolId;
|
|
125
172
|
if (query.chainId)
|
|
126
173
|
campaignQuery.chainId = query.chainId;
|
|
127
|
-
|
|
128
|
-
const campaigns = (yield (0, exports.fetchAllMerklCampaigns)(campaignQuery))
|
|
174
|
+
const campaigns = (yield fetchAllMerklCampaignsCached(campaignQuery))
|
|
129
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); });
|
|
130
176
|
const campaignsByOpportunity = {};
|
|
131
177
|
campaigns.forEach((c) => {
|
|
@@ -137,9 +183,9 @@ const fetchMerklOpportunitiesAt = (query, timestamp) => __awaiter(void 0, void 0
|
|
|
137
183
|
if (!opportunityIds.length)
|
|
138
184
|
return [];
|
|
139
185
|
const types = (_a = query.type) === null || _a === void 0 ? void 0 : _a.split(',').filter(Boolean);
|
|
140
|
-
const opportunities = (yield (
|
|
141
|
-
.filter((o) => !(types === null || types === void 0 ? void 0 : types.length) || types.includes(o.type));
|
|
142
|
-
const aprs = yield mapWithConcurrency(opportunities, APR_RECORDS_CONCURRENCY, (o) => (
|
|
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));
|
|
143
189
|
return opportunities.flatMap((o, i) => {
|
|
144
190
|
var _a, _b, _c;
|
|
145
191
|
const apr = aprs[i];
|
|
@@ -154,9 +200,11 @@ const fetchMerklOpportunitiesAt = (query, timestamp) => __awaiter(void 0, void 0
|
|
|
154
200
|
exports.fetchMerklOpportunitiesAt = fetchMerklOpportunitiesAt;
|
|
155
201
|
/**
|
|
156
202
|
* Live opportunities when no timestamp is given, otherwise the opportunities as they were at that
|
|
157
|
-
* unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`.
|
|
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.
|
|
158
206
|
*/
|
|
159
|
-
const fetchMerklOpportunities = (query, asOfTimestamp) => __awaiter(void 0, void 0, void 0, function* () {
|
|
160
|
-
return (asOfTimestamp === undefined ? (0, exports.fetchAllMerklOpportunities)(query) : (0, exports.fetchMerklOpportunitiesAt)(query, asOfTimestamp));
|
|
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));
|
|
161
209
|
});
|
|
162
210
|
exports.fetchMerklOpportunities = fetchMerklOpportunities;
|
package/esm/aaveV3/merkl.js
CHANGED
|
@@ -44,7 +44,7 @@ export const getMerkleCampaigns = (chainId, asOfTimestamp) => __awaiter(void 0,
|
|
|
44
44
|
mainProtocolId: 'aave',
|
|
45
45
|
chainId: chainId.toString(),
|
|
46
46
|
status: OpportunityStatus.LIVE,
|
|
47
|
-
}, asOfTimestamp);
|
|
47
|
+
}, asOfTimestamp, (o) => { var _a; return !((_a = o.type) === null || _a === void 0 ? void 0 : _a.startsWith('AAVE_V4_')); });
|
|
48
48
|
const relevantOpportunities = opportunities
|
|
49
49
|
.filter((o) => o.chainId === chainId)
|
|
50
50
|
.filter((o) => o.status === OpportunityStatus.LIVE);
|
package/esm/services/merkl.d.ts
CHANGED
|
@@ -13,18 +13,26 @@ export declare const fetchAllMerklCampaigns: (query: Record<string, string>) =>
|
|
|
13
13
|
export declare const fetchMerklOpportunitiesByIds: (ids: string[]) => Promise<MerklOpportunity[]>;
|
|
14
14
|
/**
|
|
15
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
|
|
17
|
-
*
|
|
18
|
-
*
|
|
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.
|
|
19
22
|
*/
|
|
20
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;
|
|
21
26
|
/**
|
|
22
27
|
* Reconstructs the opportunities that were live at `timestamp` (unix seconds), shaped like the
|
|
23
28
|
* live listing so the per-protocol reward mappers can consume either without knowing which they got:
|
|
24
|
-
* 1.
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
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;
|
|
28
36
|
* 3. each one's `apr` is replaced with the value Merkl recorded at the timestamp, and ones with no
|
|
29
37
|
* record then are dropped, since nothing was being computed for them.
|
|
30
38
|
* `status` is forced to LIVE so status filters downstream keep working, `campaigns` carries the
|
|
@@ -32,9 +40,11 @@ export declare const fetchMerklOpportunityAprAt: (opportunityId: string, timesta
|
|
|
32
40
|
* when Merkl no longer serves one for the opportunity (it drops them once an opportunity is PAST).
|
|
33
41
|
* `query.status` is ignored: it describes the present, not the requested moment.
|
|
34
42
|
*/
|
|
35
|
-
export declare const fetchMerklOpportunitiesAt: (query: Record<string, string>, timestamp: number) => Promise<MerklOpportunity[]>;
|
|
43
|
+
export declare const fetchMerklOpportunitiesAt: (query: Record<string, string>, timestamp: number, isRelevant?: (opportunity: MerklOpportunity) => boolean) => Promise<MerklOpportunity[]>;
|
|
36
44
|
/**
|
|
37
45
|
* Live opportunities when no timestamp is given, otherwise the opportunities as they were at that
|
|
38
|
-
* unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`.
|
|
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.
|
|
39
49
|
*/
|
|
40
|
-
export declare const fetchMerklOpportunities: (query: Record<string, string>, asOfTimestamp?: number) => Promise<MerklOpportunity[]>;
|
|
50
|
+
export declare const fetchMerklOpportunities: (query: Record<string, string>, asOfTimestamp?: number, isRelevant?: (opportunity: MerklOpportunity) => boolean) => Promise<MerklOpportunity[]>;
|
package/esm/services/merkl.js
CHANGED
|
@@ -7,6 +7,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
7
7
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
8
|
});
|
|
9
9
|
};
|
|
10
|
+
import memoize from 'memoizee';
|
|
10
11
|
import { OpportunityStatus, } from '../types';
|
|
11
12
|
import { LONGER_TIMEOUT } from './utils';
|
|
12
13
|
const MERKL_API_URL = 'https://fe.defisaver.com/api/merkl';
|
|
@@ -19,11 +20,18 @@ const OPPORTUNITY_ID_BATCH_SIZE = 50;
|
|
|
19
20
|
// APR history is fetched per opportunity, so historical lookups are throttled to keep a block with
|
|
20
21
|
// many live campaigns from firing every request at once.
|
|
21
22
|
const APR_RECORDS_CONCURRENCY = 10;
|
|
22
|
-
const
|
|
23
|
+
const SECONDS_PER_HOUR = 60 * 60;
|
|
24
|
+
const SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;
|
|
25
|
+
// Historical lookups describe the past, so their responses are reused for a while: a job that
|
|
26
|
+
// walks many blocks (or fetches several protocols/chains at one block in parallel) would otherwise
|
|
27
|
+
// re-request the same campaign lists, opportunities and APR buckets for every block.
|
|
28
|
+
const HISTORY_CACHE_TTL = 5 * 60 * 1000;
|
|
23
29
|
const merklGet = (url, query, label) => __awaiter(void 0, void 0, void 0, function* () {
|
|
24
30
|
const res = yield fetch(`${url}?${new URLSearchParams(query)}`, { signal: AbortSignal.timeout(LONGER_TIMEOUT) });
|
|
25
|
-
if (!res.ok)
|
|
26
|
-
|
|
31
|
+
if (!res.ok) {
|
|
32
|
+
const body = yield res.text().catch(() => '');
|
|
33
|
+
throw new Error(`Failed to fetch Merkl ${label} (HTTP ${res.status}${body ? `: ${body.slice(0, 200)}` : ''})`);
|
|
34
|
+
}
|
|
27
35
|
return res.json();
|
|
28
36
|
});
|
|
29
37
|
/**
|
|
@@ -56,6 +64,11 @@ export const fetchAllMerklOpportunities = (query) => __awaiter(void 0, void 0, v
|
|
|
56
64
|
export const fetchAllMerklCampaigns = (query) => __awaiter(void 0, void 0, void 0, function* () {
|
|
57
65
|
return (fetchAllMerklPages(MERKL_CAMPAIGNS_URL, query, 'campaigns', MERKL_MAX_PAGE_ITEMS));
|
|
58
66
|
});
|
|
67
|
+
const fetchAllMerklCampaignsCached = memoize(fetchAllMerklCampaigns, {
|
|
68
|
+
promise: true,
|
|
69
|
+
maxAge: HISTORY_CACHE_TTL,
|
|
70
|
+
normalizer: ([query]) => JSON.stringify(Object.entries(query).sort()),
|
|
71
|
+
});
|
|
59
72
|
/**
|
|
60
73
|
* Fetches the opportunities with the given Merkl-internal ids, regardless of their current status.
|
|
61
74
|
* Ids Merkl no longer serves (hidden or test campaigns) are simply absent from the result.
|
|
@@ -71,24 +84,51 @@ export const fetchMerklOpportunitiesByIds = (ids) => __awaiter(void 0, void 0, v
|
|
|
71
84
|
return data;
|
|
72
85
|
});
|
|
73
86
|
});
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
export const fetchMerklOpportunityAprAt = (opportunityId, timestamp) => __awaiter(void 0, void 0, void 0, function* () {
|
|
81
|
-
var _a;
|
|
87
|
+
const fetchMerklOpportunitiesByIdsCached = memoize(fetchMerklOpportunitiesByIds, {
|
|
88
|
+
promise: true,
|
|
89
|
+
maxAge: HISTORY_CACHE_TTL,
|
|
90
|
+
normalizer: ([ids]) => [...ids].sort().join(','),
|
|
91
|
+
});
|
|
92
|
+
const fetchLatestMerklAprRecord = (opportunityId, grain, to) => __awaiter(void 0, void 0, void 0, function* () {
|
|
82
93
|
const records = yield merklGet(`${MERKL_OPPORTUNITIES_URL}/${opportunityId}/apr-records`, {
|
|
83
|
-
grain
|
|
84
|
-
from: (
|
|
85
|
-
to:
|
|
94
|
+
grain,
|
|
95
|
+
from: (to - SECONDS_PER_DAY).toString(),
|
|
96
|
+
to: to.toString(),
|
|
86
97
|
items: '1',
|
|
87
98
|
}, `APR records for opportunity ${opportunityId}`);
|
|
88
99
|
if (!Array.isArray(records))
|
|
89
100
|
throw new Error(`Invalid Merkl APR records response for opportunity ${opportunityId}`);
|
|
90
|
-
return
|
|
101
|
+
return records[0];
|
|
91
102
|
});
|
|
103
|
+
/**
|
|
104
|
+
* Returns the reward APR Merkl recorded for the opportunity at the given unix timestamp (seconds),
|
|
105
|
+
* or `undefined` when no campaign was computing for it then. Records are buckets keyed by their
|
|
106
|
+
* start, newest first, and each carries the last value recorded in the bucket. The hourly bucket of
|
|
107
|
+
* the timestamp's hour is used when Merkl still has it — it keeps hourly history for roughly the
|
|
108
|
+
* last ten weeks — and the daily bucket of the timestamp's day otherwise. Either window is a day
|
|
109
|
+
* wide to tolerate computation gaps and aligned to the bucket, so every block within one hour asks
|
|
110
|
+
* for (and caches) the same records.
|
|
111
|
+
*/
|
|
112
|
+
export const fetchMerklOpportunityAprAt = (opportunityId, timestamp) => __awaiter(void 0, void 0, void 0, function* () {
|
|
113
|
+
var _a;
|
|
114
|
+
const hour = Math.floor(timestamp / SECONDS_PER_HOUR) * SECONDS_PER_HOUR;
|
|
115
|
+
const hourly = yield fetchLatestMerklAprRecord(opportunityId, 'HOUR', hour);
|
|
116
|
+
if (hourly)
|
|
117
|
+
return hourly.apr;
|
|
118
|
+
const day = Math.floor(timestamp / SECONDS_PER_DAY) * SECONDS_PER_DAY;
|
|
119
|
+
return (_a = (yield fetchLatestMerklAprRecord(opportunityId, 'DAY', day))) === null || _a === void 0 ? void 0 : _a.apr;
|
|
120
|
+
});
|
|
121
|
+
const fetchMerklOpportunityAprAtCached = memoize(fetchMerklOpportunityAprAt, {
|
|
122
|
+
promise: true,
|
|
123
|
+
maxAge: HISTORY_CACHE_TTL,
|
|
124
|
+
normalizer: ([opportunityId, timestamp]) => `${opportunityId}:${Math.floor(timestamp / SECONDS_PER_HOUR)}`,
|
|
125
|
+
});
|
|
126
|
+
/** Drops every cached historical response (campaign lists, opportunities, APR buckets). */
|
|
127
|
+
export const clearMerklHistoryCache = () => {
|
|
128
|
+
fetchAllMerklCampaignsCached.clear();
|
|
129
|
+
fetchMerklOpportunitiesByIdsCached.clear();
|
|
130
|
+
fetchMerklOpportunityAprAtCached.clear();
|
|
131
|
+
};
|
|
92
132
|
const mapWithConcurrency = (items, concurrency, fn) => __awaiter(void 0, void 0, void 0, function* () {
|
|
93
133
|
const results = [];
|
|
94
134
|
for (let i = 0; i < items.length; i += concurrency) {
|
|
@@ -99,10 +139,13 @@ const mapWithConcurrency = (items, concurrency, fn) => __awaiter(void 0, void 0,
|
|
|
99
139
|
/**
|
|
100
140
|
* Reconstructs the opportunities that were live at `timestamp` (unix seconds), shaped like the
|
|
101
141
|
* live listing so the per-protocol reward mappers can consume either without knowing which they got:
|
|
102
|
-
* 1.
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
142
|
+
* 1. every LIVE or PAST campaign for the protocol (and chain, when the query names one) is listed
|
|
143
|
+
* once per cache period — the list is block-independent, the exact window check happens here —
|
|
144
|
+
* and the ones whose [start, end] covers the timestamp identify the opportunities rewarded
|
|
145
|
+
* then (the live listing can't: campaigns live then are mostly PAST now and ones live now
|
|
146
|
+
* didn't exist then);
|
|
147
|
+
* 2. those opportunities are loaded by id (works for PAST ones too) and narrowed to `query.type`
|
|
148
|
+
* and `isRelevant`, so no APR history is fetched for opportunities the caller would discard;
|
|
106
149
|
* 3. each one's `apr` is replaced with the value Merkl recorded at the timestamp, and ones with no
|
|
107
150
|
* record then are dropped, since nothing was being computed for them.
|
|
108
151
|
* `status` is forced to LIVE so status filters downstream keep working, `campaigns` carries the
|
|
@@ -110,15 +153,14 @@ const mapWithConcurrency = (items, concurrency, fn) => __awaiter(void 0, void 0,
|
|
|
110
153
|
* when Merkl no longer serves one for the opportunity (it drops them once an opportunity is PAST).
|
|
111
154
|
* `query.status` is ignored: it describes the present, not the requested moment.
|
|
112
155
|
*/
|
|
113
|
-
export const fetchMerklOpportunitiesAt = (
|
|
156
|
+
export const fetchMerklOpportunitiesAt = (query_1, timestamp_1, ...args_1) => __awaiter(void 0, [query_1, timestamp_1, ...args_1], void 0, function* (query, timestamp, isRelevant = () => true) {
|
|
114
157
|
var _a;
|
|
115
|
-
const campaignQuery = { status: 'LIVE,PAST'
|
|
158
|
+
const campaignQuery = { status: 'LIVE,PAST' };
|
|
116
159
|
if (query.mainProtocolId)
|
|
117
160
|
campaignQuery.mainProtocolId = query.mainProtocolId;
|
|
118
161
|
if (query.chainId)
|
|
119
162
|
campaignQuery.chainId = query.chainId;
|
|
120
|
-
|
|
121
|
-
const campaigns = (yield fetchAllMerklCampaigns(campaignQuery))
|
|
163
|
+
const campaigns = (yield fetchAllMerklCampaignsCached(campaignQuery))
|
|
122
164
|
.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); });
|
|
123
165
|
const campaignsByOpportunity = {};
|
|
124
166
|
campaigns.forEach((c) => {
|
|
@@ -130,9 +172,9 @@ export const fetchMerklOpportunitiesAt = (query, timestamp) => __awaiter(void 0,
|
|
|
130
172
|
if (!opportunityIds.length)
|
|
131
173
|
return [];
|
|
132
174
|
const types = (_a = query.type) === null || _a === void 0 ? void 0 : _a.split(',').filter(Boolean);
|
|
133
|
-
const opportunities = (yield
|
|
134
|
-
.filter((o) => !(types === null || types === void 0 ? void 0 : types.length) || types.includes(o.type));
|
|
135
|
-
const aprs = yield mapWithConcurrency(opportunities, APR_RECORDS_CONCURRENCY, (o) =>
|
|
175
|
+
const opportunities = (yield fetchMerklOpportunitiesByIdsCached(opportunityIds))
|
|
176
|
+
.filter((o) => (!(types === null || types === void 0 ? void 0 : types.length) || types.includes(o.type)) && isRelevant(o));
|
|
177
|
+
const aprs = yield mapWithConcurrency(opportunities, APR_RECORDS_CONCURRENCY, (o) => fetchMerklOpportunityAprAtCached(o.id, timestamp));
|
|
136
178
|
return opportunities.flatMap((o, i) => {
|
|
137
179
|
var _a, _b, _c;
|
|
138
180
|
const apr = aprs[i];
|
|
@@ -146,8 +188,10 @@ export const fetchMerklOpportunitiesAt = (query, timestamp) => __awaiter(void 0,
|
|
|
146
188
|
});
|
|
147
189
|
/**
|
|
148
190
|
* Live opportunities when no timestamp is given, otherwise the opportunities as they were at that
|
|
149
|
-
* unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`.
|
|
191
|
+
* unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`. `isRelevant` only applies to the
|
|
192
|
+
* historical path, where it saves fetching APR history for opportunities the caller would discard;
|
|
193
|
+
* callers still filter the live listing themselves.
|
|
150
194
|
*/
|
|
151
|
-
export const fetchMerklOpportunities = (query, asOfTimestamp) => __awaiter(void 0, void 0, void 0, function* () {
|
|
152
|
-
return (asOfTimestamp === undefined ? fetchAllMerklOpportunities(query) : fetchMerklOpportunitiesAt(query, asOfTimestamp));
|
|
195
|
+
export const fetchMerklOpportunities = (query, asOfTimestamp, isRelevant) => __awaiter(void 0, void 0, void 0, function* () {
|
|
196
|
+
return (asOfTimestamp === undefined ? fetchAllMerklOpportunities(query) : fetchMerklOpportunitiesAt(query, asOfTimestamp, isRelevant));
|
|
153
197
|
});
|
package/package.json
CHANGED
package/src/aaveV3/merkl.ts
CHANGED
|
@@ -40,7 +40,7 @@ export const getMerkleCampaigns = async (chainId: NetworkNumber, asOfTimestamp?:
|
|
|
40
40
|
mainProtocolId: 'aave',
|
|
41
41
|
chainId: chainId.toString(),
|
|
42
42
|
status: OpportunityStatus.LIVE,
|
|
43
|
-
}, asOfTimestamp);
|
|
43
|
+
}, asOfTimestamp, (o) => !o.type?.startsWith('AAVE_V4_'));
|
|
44
44
|
const relevantOpportunities = opportunities
|
|
45
45
|
.filter((o: MerklOpportunity) => o.chainId === chainId)
|
|
46
46
|
.filter((o: MerklOpportunity) => o.status === OpportunityStatus.LIVE);
|
package/src/services/merkl.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import memoize from 'memoizee';
|
|
1
2
|
import {
|
|
2
3
|
MerklAprRecord, MerklCampaignListItem, MerklOpportunity, OpportunityStatus,
|
|
3
4
|
} from '../types';
|
|
@@ -14,11 +15,19 @@ const OPPORTUNITY_ID_BATCH_SIZE = 50;
|
|
|
14
15
|
// APR history is fetched per opportunity, so historical lookups are throttled to keep a block with
|
|
15
16
|
// many live campaigns from firing every request at once.
|
|
16
17
|
const APR_RECORDS_CONCURRENCY = 10;
|
|
17
|
-
const
|
|
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;
|
|
18
24
|
|
|
19
25
|
const merklGet = async <T>(url: string, query: Record<string, string>, label: string): Promise<T> => {
|
|
20
26
|
const res = await fetch(`${url}?${new URLSearchParams(query)}`, { signal: AbortSignal.timeout(LONGER_TIMEOUT) });
|
|
21
|
-
if (!res.ok)
|
|
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
|
+
}
|
|
22
31
|
return res.json();
|
|
23
32
|
};
|
|
24
33
|
|
|
@@ -57,6 +66,12 @@ export const fetchAllMerklCampaigns = async (query: Record<string, string>): Pro
|
|
|
57
66
|
fetchAllMerklPages<MerklCampaignListItem>(MERKL_CAMPAIGNS_URL, query, 'campaigns', MERKL_MAX_PAGE_ITEMS)
|
|
58
67
|
);
|
|
59
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
|
+
|
|
60
75
|
/**
|
|
61
76
|
* Fetches the opportunities with the given Merkl-internal ids, regardless of their current status.
|
|
62
77
|
* Ids Merkl no longer serves (hidden or test campaigns) are simply absent from the result.
|
|
@@ -75,21 +90,51 @@ export const fetchMerklOpportunitiesByIds = async (ids: string[]): Promise<Merkl
|
|
|
75
90
|
});
|
|
76
91
|
};
|
|
77
92
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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> => {
|
|
85
100
|
const records = await merklGet<unknown>(`${MERKL_OPPORTUNITIES_URL}/${opportunityId}/apr-records`, {
|
|
86
|
-
grain
|
|
87
|
-
from: (
|
|
88
|
-
to:
|
|
101
|
+
grain,
|
|
102
|
+
from: (to - SECONDS_PER_DAY).toString(),
|
|
103
|
+
to: to.toString(),
|
|
89
104
|
items: '1',
|
|
90
105
|
}, `APR records for opportunity ${opportunityId}`);
|
|
91
106
|
if (!Array.isArray(records)) throw new Error(`Invalid Merkl APR records response for opportunity ${opportunityId}`);
|
|
92
|
-
return (records as MerklAprRecord[])[0]
|
|
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
|
+
};
|
|
126
|
+
|
|
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();
|
|
93
138
|
};
|
|
94
139
|
|
|
95
140
|
const mapWithConcurrency = async <T, R>(items: T[], concurrency: number, fn: (item: T) => Promise<R>): Promise<R[]> => {
|
|
@@ -103,10 +148,13 @@ const mapWithConcurrency = async <T, R>(items: T[], concurrency: number, fn: (it
|
|
|
103
148
|
/**
|
|
104
149
|
* Reconstructs the opportunities that were live at `timestamp` (unix seconds), shaped like the
|
|
105
150
|
* live listing so the per-protocol reward mappers can consume either without knowing which they got:
|
|
106
|
-
* 1.
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
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;
|
|
110
158
|
* 3. each one's `apr` is replaced with the value Merkl recorded at the timestamp, and ones with no
|
|
111
159
|
* record then are dropped, since nothing was being computed for them.
|
|
112
160
|
* `status` is forced to LIVE so status filters downstream keep working, `campaigns` carries the
|
|
@@ -114,13 +162,16 @@ const mapWithConcurrency = async <T, R>(items: T[], concurrency: number, fn: (it
|
|
|
114
162
|
* when Merkl no longer serves one for the opportunity (it drops them once an opportunity is PAST).
|
|
115
163
|
* `query.status` is ignored: it describes the present, not the requested moment.
|
|
116
164
|
*/
|
|
117
|
-
export const fetchMerklOpportunitiesAt = async (
|
|
118
|
-
|
|
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' };
|
|
119
171
|
if (query.mainProtocolId) campaignQuery.mainProtocolId = query.mainProtocolId;
|
|
120
172
|
if (query.chainId) campaignQuery.chainId = query.chainId;
|
|
121
173
|
|
|
122
|
-
|
|
123
|
-
const campaigns = (await fetchAllMerklCampaigns(campaignQuery))
|
|
174
|
+
const campaigns = (await fetchAllMerklCampaignsCached(campaignQuery))
|
|
124
175
|
.filter((c) => c.opportunityId && +(c.startTimestamp ?? 0) <= timestamp && timestamp <= +(c.endTimestamp ?? 0));
|
|
125
176
|
const campaignsByOpportunity: Record<string, MerklCampaignListItem[]> = {};
|
|
126
177
|
campaigns.forEach((c) => {
|
|
@@ -131,10 +182,10 @@ export const fetchMerklOpportunitiesAt = async (query: Record<string, string>, t
|
|
|
131
182
|
if (!opportunityIds.length) return [];
|
|
132
183
|
|
|
133
184
|
const types = query.type?.split(',').filter(Boolean);
|
|
134
|
-
const opportunities = (await
|
|
135
|
-
.filter((o) => !types?.length || types.includes(o.type));
|
|
185
|
+
const opportunities = (await fetchMerklOpportunitiesByIdsCached(opportunityIds))
|
|
186
|
+
.filter((o) => (!types?.length || types.includes(o.type)) && isRelevant(o));
|
|
136
187
|
|
|
137
|
-
const aprs = await mapWithConcurrency(opportunities, APR_RECORDS_CONCURRENCY, (o) =>
|
|
188
|
+
const aprs = await mapWithConcurrency(opportunities, APR_RECORDS_CONCURRENCY, (o) => fetchMerklOpportunityAprAtCached(o.id, timestamp));
|
|
138
189
|
|
|
139
190
|
return opportunities.flatMap((o, i) => {
|
|
140
191
|
const apr = aprs[i];
|
|
@@ -157,8 +208,14 @@ export const fetchMerklOpportunitiesAt = async (query: Record<string, string>, t
|
|
|
157
208
|
|
|
158
209
|
/**
|
|
159
210
|
* Live opportunities when no timestamp is given, otherwise the opportunities as they were at that
|
|
160
|
-
* unix timestamp (seconds) — see `fetchMerklOpportunitiesAt`.
|
|
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.
|
|
161
214
|
*/
|
|
162
|
-
export const fetchMerklOpportunities = async (
|
|
163
|
-
|
|
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)
|
|
164
221
|
);
|