@defillama/sdk 5.0.244 → 5.0.246

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.
@@ -40,4 +40,22 @@ export declare function getAllLogs({ index, scrollTime, size, query }: {
40
40
  size?: number;
41
41
  query?: object;
42
42
  }): Promise<any[]>;
43
+ export type DataIssue = {
44
+ entity_type: 'protocol' | 'chain' | 'coin' | 'stablecoin' | 'rwa' | 'market' | 'pool' | 'table' | 'job';
45
+ entity_id: string | null;
46
+ parent_id: string | null;
47
+ name: string;
48
+ metric: string;
49
+ day: string | null;
50
+ value: number | null;
51
+ baseline: number | null;
52
+ check: string;
53
+ type: 'spike' | 'drop' | 'gap' | 'stale' | 'missing' | 'mismatch' | 'other';
54
+ state: 'live' | 'removed' | 'blocked' | 'disabled';
55
+ message: string;
56
+ };
57
+ export declare const dayOf: (unixSeconds: number) => string;
58
+ export declare function reportIssues(issues: DataIssue[], { limitMs }?: {
59
+ limitMs?: number;
60
+ }): Promise<void>;
43
61
  export {};
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dayOf = void 0;
3
4
  exports.getClient = getClient;
4
5
  exports.writeLog = writeLog;
5
6
  exports.addDebugLog = addDebugLog;
@@ -7,6 +8,7 @@ exports.addRuntimeLog = addRuntimeLog;
7
8
  exports.addErrorLog = addErrorLog;
8
9
  exports.search = search;
9
10
  exports.getAllLogs = getAllLogs;
11
+ exports.reportIssues = reportIssues;
10
12
  const elasticsearch_1 = require("@elastic/elasticsearch");
11
13
  const env_1 = require("./env");
12
14
  const debugLog_1 = require("./debugLog");
@@ -111,3 +113,25 @@ async function getAllLogs({ index, scrollTime = '1m', size = 100000, query = {
111
113
  }
112
114
  return allLogs;
113
115
  }
116
+ const dayOf = (unixSeconds) => new Date(unixSeconds * 1000).toISOString().slice(0, 10);
117
+ exports.dayOf = dayOf;
118
+ // Never rejects. One bulk request, time-limited, as a write to a down Elasticsearch takes up to 20 s.
119
+ async function reportIssues(issues, { limitMs = 50000 } = {}) {
120
+ const client = getClient();
121
+ if (!client) {
122
+ console.warn('Elasticsearch client not configured, skipping reportIssues');
123
+ return;
124
+ }
125
+ const cutoff = (0, exports.dayOf)(Date.now() / 1000 - 7 * 86400); // a check can find old items again on each run
126
+ const timestamp = +Date.now();
127
+ const docs = issues
128
+ .filter((i) => !i.day || i.day >= cutoff)
129
+ .map(({ value, baseline, ...issue }) => ({ ...issue, value, baseline, timestamp, deviation: value != null && baseline ? (value - baseline) / baseline : null }));
130
+ if (!docs.length)
131
+ return;
132
+ const write = client.bulk({ index: addYearAndMonth('data-issues'), operations: docs.flatMap((doc) => [{ index: {} }, doc]), timeout: `${limitMs}ms` })
133
+ .then((res) => { if (res.errors)
134
+ console.error('data-issues bulk write: some items failed'); })
135
+ .catch((e) => console.error('data-issues write failed:', e === null || e === void 0 ? void 0 : e.message));
136
+ await Promise.race([write, new Promise((resolve) => { var _a, _b; return (_b = (_a = setTimeout(resolve, limitMs)).unref) === null || _b === void 0 ? void 0 : _b.call(_a); })]);
137
+ }
package/build/util/env.js CHANGED
@@ -19,7 +19,7 @@ exports.getWhitelistedRPCs = getWhitelistedRPCs;
19
19
  exports.shouldSkipBlockValidation = shouldSkipBlockValidation;
20
20
  exports.getBoolEnvValue = getBoolEnvValue;
21
21
  exports.whitelistedEnvConstants = [
22
- 'R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'TRON_PRO_API_KEY', 'COINS_API_KEY', 'INTERNAL_API_KEY',
22
+ 'R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_CONFIG', 'TRON_PRO_API_KEY', 'COINS_API_KEY', 'INTERNAL_API_KEY',
23
23
  'ELASTICSEARCH_CONFIG', 'GRAPH_API_KEY', 'LLAMA_INDEXER_V2_ENDPOINT', 'LLAMA_INDEXER_V2_API_KEY', 'LLAMA_INDEXER_TIMEOUT_MS',
24
24
  'LLAMA_INDEXER_V4_ENDPOINT', 'LLAMA_INDEXER_V4_API_KEY', 'LLAMA_INDEXER_PREFER_V4', 'LLAMA_INDEXER_V4_ONLY_CHAINS',
25
25
  'LLAMA_INDEXER_SQL_ENDPOINT', 'LLAMA_INDEXER_SQL_USER', 'LLAMA_INDEXER_SQL_PASSWORD',
@@ -12,7 +12,7 @@ type GetLogsOptions = {
12
12
  keys: string[];
13
13
  fromBlock: number;
14
14
  toBlock: number;
15
- topics?: (string | null)[];
15
+ topics?: (string | string[] | null)[];
16
16
  chain?: Chain;
17
17
  provider?: ethers.Provider;
18
18
  };
@@ -14,6 +14,7 @@ const general_1 = require("../general");
14
14
  const ethers_1 = require("ethers");
15
15
  const common_1 = require("./common");
16
16
  const debugLog_1 = require("./debugLog");
17
+ const callStats_1 = require("./callStats");
17
18
  const promisePool_1 = __importDefault(require("./promisePool"));
18
19
  var blocks_1 = require("./blocks");
19
20
  Object.defineProperty(exports, "getLatestBlock", { enumerable: true, get: function () { return blocks_1.getLatestBlock; } });
@@ -87,6 +88,7 @@ async function _getLogs(params) {
87
88
  };
88
89
  try {
89
90
  const partLogs = await provider.getLogs(logParams);
91
+ (0, callStats_1.recordLogs)('rpc', params.chain, partLogs.length);
90
92
  logs = logs.concat(partLogs);
91
93
  currentBlock = nextBlock;
92
94
  }
@@ -1,4 +1,5 @@
1
1
  import { Address } from "../types";
2
+ import { GetLogsTopics } from "./logs";
2
3
  import { GetTransactionOptions } from "./transactions";
3
4
  export type IndexerVersion = "v2" | "v4";
4
5
  export declare function getChainIndexerVersion(chain: string): IndexerVersion;
@@ -8,7 +9,7 @@ export type IndexerGetLogsOptions = {
8
9
  topic?: string;
9
10
  fromBlock?: number;
10
11
  toBlock?: number;
11
- topics?: (string | null)[];
12
+ topics?: GetLogsTopics;
12
13
  extraTopics?: string[];
13
14
  chain?: string;
14
15
  eventAbi?: string | any;
@@ -14,6 +14,7 @@ exports.isIndexer2Enabled = isIndexer2Enabled;
14
14
  const axios_1 = __importDefault(require("axios"));
15
15
  const http_1 = __importDefault(require("http"));
16
16
  const https_1 = __importDefault(require("https"));
17
+ const p_limit_1 = __importDefault(require("p-limit"));
17
18
  const promises_1 = require("stream/promises");
18
19
  const stream_json_1 = require("stream-json");
19
20
  const Pick_1 = require("stream-json/filters/Pick");
@@ -142,6 +143,34 @@ function getTransactionCursor(transaction) {
142
143
  return;
143
144
  return { after_block: +transaction.block_number, after_index: +transaction.transaction_index };
144
145
  }
146
+ const TOPIC_QUERY_CONCURRENCY = 5;
147
+ const normalizeTopic = (topic) => (0, logs_decode_shared_1.padTopic32)(topic.toLowerCase());
148
+ // The indexer filters a topic position by a single value, while eth_getLogs topics also take
149
+ // null or [] (any topic) and arrays (any of their values). OR'd positions become one query per
150
+ // combination of values; the combinations match disjoint sets of logs.
151
+ function getTopicQueries(topics = []) {
152
+ let queries = [{}];
153
+ topics.slice(0, 4).forEach((filter, i) => {
154
+ const values = Array.isArray(filter) ? filter : [filter];
155
+ if (!values.length || values.some((v) => !v))
156
+ return;
157
+ const unique = [...new Map(values.map((v) => [normalizeTopic(v), v])).values()];
158
+ queries = queries.flatMap((q) => unique.map((v) => ({ ...q, [`topic${i}`]: v })));
159
+ });
160
+ return queries;
161
+ }
162
+ // Guards against the indexer ignoring a topic filter: such rows are dropped before decoding.
163
+ function getTopicMatcher(query) {
164
+ const expected = Object.entries(query).map(([key, value]) => [key, normalizeTopic(value)]);
165
+ return (log) => expected.every(([key, value]) => typeof log[key] === "string" && normalizeTopic(log[key]) === value);
166
+ }
167
+ // Each topic query returns rows in (block, log index) order; rows merged from OR'd topic queries
168
+ // are sorted back into it, as eth_getLogs returns them.
169
+ function compareLogRows(a, b) {
170
+ var _a, _b, _c, _d, _e, _f;
171
+ return +((_a = a.block_number) !== null && _a !== void 0 ? _a : a.blockNumber) - +((_b = b.block_number) !== null && _b !== void 0 ? _b : b.blockNumber)
172
+ || +((_d = (_c = a.log_index) !== null && _c !== void 0 ? _c : a.logIndex) !== null && _d !== void 0 ? _d : a.index) - +((_f = (_e = b.log_index) !== null && _e !== void 0 ? _e : b.logIndex) !== null && _f !== void 0 ? _f : b.index);
173
+ }
145
174
  function safePush(target, source) {
146
175
  for (const row of source)
147
176
  target.push(row);
@@ -165,6 +194,11 @@ function assertCursorAdvances(next, previous) {
165
194
  if (!advances)
166
195
  throw new Error("Indexer v4 pagination cursor did not advance");
167
196
  }
197
+ // chain of an indexer query, for call stats: every page request is counted against it
198
+ function chainOfParams(params) {
199
+ var _a;
200
+ return (_a = allChainIdChainMapping[params === null || params === void 0 ? void 0 : params.chainId]) !== null && _a !== void 0 ? _a : callStats_1.OTHER_CHAIN;
201
+ }
168
202
  // Translate the public offset/limit contract into keyset pagination. Even all=false
169
203
  // may need several requests: the v4 server caps offsets, not the public SDK API.
170
204
  async function* getV4Pages(path, key, params, limit, offset, all, getCursor) {
@@ -175,8 +209,10 @@ async function* getV4Pages(path, key, params, limit, offset, all, getCursor) {
175
209
  let cursor;
176
210
  let remainingOffset = offset;
177
211
  let remainingLimit = all ? Infinity : limit;
212
+ const chain = chainOfParams(params);
178
213
  while (remainingLimit > 0) {
179
214
  const pageParams = { ...params, limit, offset: 0, includeTotal: false, ...cursor };
215
+ (0, callStats_1.recordMethod)(callStats_1.INDEXER_METHOD, chain);
180
216
  const response = await axiosInstances.v4(path, {
181
217
  params: pageParams,
182
218
  ...(key === "transfers" ? { responseType: "text", transformResponse: (data) => data } : {}),
@@ -186,6 +222,8 @@ async function* getV4Pages(path, key, params, limit, offset, all, getCursor) {
186
222
  const page = data[key];
187
223
  if (!Array.isArray(page))
188
224
  throw new Error(`Indexer v4 returned an invalid ${key} response`);
225
+ if (key === "logs")
226
+ (0, callStats_1.recordLogs)('indexer', chain, page.length);
189
227
  // Capture the cursor before consumers normalize/mutate the raw rows.
190
228
  const next = getCursor(page[page.length - 1]);
191
229
  const result = applyLocalOffset(page, remainingOffset);
@@ -208,10 +246,14 @@ async function* getIndexerPages(version, path, key, params, limit, offset, all,
208
246
  return;
209
247
  }
210
248
  let count = 0;
249
+ const chain = chainOfParams(params);
211
250
  do {
251
+ (0, callStats_1.recordMethod)(callStats_1.INDEXER_METHOD, chain);
212
252
  const { data } = await axiosInstances.v2(path, { params: { ...params, limit, offset } })
213
253
  .catch((e) => { throw (0, common_1.formError)(e); });
214
254
  const rows = data[key];
255
+ if (key === "logs" && Array.isArray(rows))
256
+ (0, callStats_1.recordLogs)('indexer', chain, rows.length);
215
257
  yield rows;
216
258
  count += rows.length;
217
259
  if (!rows.length || rows.length < limit || (key === "logs" && typeof data.totalCount === "number" && data.totalCount <= count))
@@ -231,6 +273,7 @@ async function getChainIndexStatus(version) {
231
273
  return state.chainIndexStatus;
232
274
  state.timestamp = Date.now();
233
275
  state.chainIndexStatus = (async () => {
276
+ (0, callStats_1.recordMethod)(callStats_1.INDEXER_METHOD); // serves every chain: counted under _other
234
277
  const { data: { syncStatus }, } = await axiosInstances[version].get(`/sync`).catch((e) => { throw (0, common_1.formError)(e); });
235
278
  const info = {};
236
279
  syncStatus.forEach((d) => {
@@ -251,10 +294,11 @@ async function getChainIndexStatus(version) {
251
294
  return state.chainIndexStatus;
252
295
  }
253
296
  async function streamLogs(opts) {
254
- const { path, version, onItem, onChunkStats, shouldStop } = opts;
297
+ const { path, version, chain, onItem, onChunkStats, shouldStop } = opts;
255
298
  const controller = new AbortController();
256
299
  let bytesReceived = 0;
257
300
  let itemsProcessed = 0;
301
+ (0, callStats_1.recordMethod)(callStats_1.INDEXER_METHOD, chain);
258
302
  const res = await axiosInstances[version].get(path, {
259
303
  responseType: "stream",
260
304
  timeout: INDEXER_REQUEST_TIMEOUT_MS,
@@ -296,6 +340,9 @@ async function streamLogs(opts) {
296
340
  if (!stopped)
297
341
  throw processingError !== null && processingError !== void 0 ? processingError : e;
298
342
  }
343
+ finally {
344
+ (0, callStats_1.recordLogs)('indexer', chain, itemsProcessed); // rows received, including those of a stream that then failed
345
+ }
299
346
  onChunkStats === null || onChunkStats === void 0 ? void 0 : onChunkStats({ chunkSize: 0, bytesReceived, itemsProcessed });
300
347
  }
301
348
  async function decodeStreamingLogs(logs, transformLog, batchDecoder, onlyArgs) {
@@ -320,7 +367,8 @@ async function getLogs(options) {
320
367
  if (processor && typeof options.collect === "undefined" && clientStreaming) {
321
368
  options = { ...options, collect: false };
322
369
  }
323
- const { chain, fromBlock, toBlock, topic, topic1, topic2, topic3, topics, transformLog, } = await (0, logs_1.getLogParams)(options, true);
370
+ const { chain, fromBlock, toBlock, topic, topics, transformLog, } = await (0, logs_1.getLogParams)(options, true);
371
+ const topicQueries = getTopicQueries(topics);
324
372
  const viemFastPath =
325
373
  // Preserve the historical streaming shape, including entireLog: the viem
326
374
  // fast path exposes args without adding the buffered decoder's parsedLog.
@@ -427,18 +475,29 @@ async function getLogs(options) {
427
475
  safePush(collected, transformedLogs);
428
476
  }
429
477
  };
430
- for (const chunk of addressChunks) {
431
- if (Array.isArray(chunk) && chunk.length === 0)
432
- throw new Error("Address chunk cannot be empty");
478
+ const transformBatch = [];
479
+ // applies offset/limit and decodes in micro batches; false once the limit is reached
480
+ const take = async (raw) => {
481
+ if (remainingOffset > 0) {
482
+ remainingOffset--;
483
+ return true;
484
+ }
485
+ if (remainingLimit <= 0)
486
+ return false;
487
+ transformBatch.push(raw);
488
+ remainingLimit--;
489
+ if (transformBatch.length >= MICRO_BATCH_SIZE) {
490
+ const batch = transformBatch.splice(0, MICRO_BATCH_SIZE);
491
+ await flushBatch(batch);
492
+ }
493
+ return remainingLimit > 0;
494
+ };
495
+ const streamTopicQuery = async (chunk, topicQuery, onRow) => {
433
496
  const qs = new URLSearchParams();
434
497
  qs.set("chainId", String(chainId));
435
- qs.set("topic0", topic);
436
- if (topic1)
437
- qs.set("topic1", topic1);
438
- if (topic2)
439
- qs.set("topic2", topic2);
440
- if (topic3)
441
- qs.set("topic3", topic3);
498
+ for (const [key, value] of Object.entries(topicQuery))
499
+ qs.set(key, value);
500
+ const matchesTopics = getTopicMatcher(topicQuery);
442
501
  if (fromBlock != null)
443
502
  qs.set("from_block", String(fromBlock));
444
503
  if (toBlock != null)
@@ -449,11 +508,11 @@ async function getLogs(options) {
449
508
  qs.set("noTarget", "true");
450
509
  qs.set("limit", "all");
451
510
  qs.set("offset", "0");
452
- const transformBatch = [];
453
511
  let stopNow = false;
454
512
  await streamLogs({
455
513
  path: `/logs?${qs.toString()}`,
456
514
  version: indexerVersion,
515
+ chain,
457
516
  onItem: async (raw) => {
458
517
  var _a, _b, _c;
459
518
  if (stopNow)
@@ -461,28 +520,34 @@ async function getLogs(options) {
461
520
  if (indexerVersion === "v4")
462
521
  (0, indexer_compatibility_1.normalizeV4Row)(raw, "logs");
463
522
  const okAddress = !addressSet.size || addressSet.has((_c = (_b = ((_a = raw.source) !== null && _a !== void 0 ? _a : raw.address)) === null || _b === void 0 ? void 0 : _b.toLowerCase) === null || _c === void 0 ? void 0 : _c.call(_b));
464
- if (!okAddress)
465
- return;
466
- if (remainingOffset > 0) {
467
- remainingOffset--;
468
- return;
469
- }
470
- if (remainingLimit <= 0) {
523
+ if (okAddress && matchesTopics(raw) && !(await onRow(raw)))
471
524
  stopNow = true;
472
- return;
473
- }
474
- transformBatch.push(raw);
475
- remainingLimit--;
476
- if (remainingLimit <= 0)
477
- stopNow = true;
478
- if (transformBatch.length >= MICRO_BATCH_SIZE) {
479
- const batch = transformBatch.splice(0, MICRO_BATCH_SIZE);
480
- await flushBatch(batch);
481
- }
482
525
  },
483
526
  shouldStop: () => stopNow,
484
527
  onChunkStats: onWireStats,
485
528
  });
529
+ };
530
+ for (const chunk of addressChunks) {
531
+ if (Array.isArray(chunk) && chunk.length === 0)
532
+ throw new Error("Address chunk cannot be empty");
533
+ if (topicQueries.length === 1) {
534
+ await streamTopicQuery(chunk, topicQueries[0], take);
535
+ }
536
+ else {
537
+ // OR'd topic queries stream in parallel; their rows are merged into block order before
538
+ // offset/limit apply, so each query needs at most offset + limit rows
539
+ const maxRows = remainingOffset + remainingLimit;
540
+ const limitTopicQuery = (0, p_limit_1.default)(TOPIC_QUERY_CONCURRENCY);
541
+ const rowsByQuery = await Promise.all(topicQueries.map((topicQuery) => limitTopicQuery(async () => {
542
+ const queryRows = [];
543
+ await streamTopicQuery(chunk, topicQuery, (raw) => queryRows.push(raw) < maxRows);
544
+ return queryRows;
545
+ })));
546
+ for (const raw of rowsByQuery.flat().sort(compareLogRows)) {
547
+ if (!(await take(raw)))
548
+ break;
549
+ }
550
+ }
486
551
  if (transformBatch.length > 0) {
487
552
  await flushBatch(transformBatch.splice(0, transformBatch.length));
488
553
  }
@@ -504,36 +569,63 @@ async function getLogs(options) {
504
569
  (0, debugLog_1.debugLog)("[Indexer] Pulling logs " + debugTimeKey);
505
570
  console.time(debugTimeKey);
506
571
  }
572
+ const transformBatchFn = transformLog.batch || ((logs) => Promise.all(logs.map((log) => transformLog(log))));
573
+ const processLogs = async (filtered) => {
574
+ const t0 = Date.now();
575
+ for (const log of filtered) {
576
+ (0, logs_decode_shared_1.normalizeLog)(log, true);
577
+ }
578
+ const transformedLogs = await transformBatchFn(filtered);
579
+ const transformedPair = filtered.map((log, idx) => ({ raw: log, transformed: transformedLogs[idx] }));
580
+ const decodeTime = Date.now() - t0;
581
+ if (onDecodeStats && filtered.length > 0)
582
+ onDecodeStats({ batchSize: filtered.length, decodeTime, itemsDecoded: filtered.length });
583
+ if (processor)
584
+ await processor(transformedPair.map((i) => i.transformed));
585
+ if (options.collect !== false) {
586
+ safePush(allLogsPairs, transformedPair);
587
+ }
588
+ };
507
589
  for (const chunk of addressChunks) {
508
590
  if (Array.isArray(chunk) && chunk.length === 0)
509
591
  throw new Error("Address chunk cannot be empty");
510
- const params = {
511
- addresses: hasAddressFilter ? chunk === null || chunk === void 0 ? void 0 : chunk.join(",") : undefined,
512
- chainId, topic0: topic, from_block: fromBlock, to_block: toBlock,
513
- topic1, topic2, topic3, noTarget,
514
- };
515
- for await (const rows of getIndexerPages(indexerVersion, "/logs", "logs", params, limit, initialOffset, all, getLogCursor)) {
516
- const filtered = rows.filter((l) => {
517
- var _a, _b, _c;
518
- const isWhitelisted = !addressSet.size || addressSet.has((_c = (_b = ((_a = l.source) !== null && _a !== void 0 ? _a : l.address)) === null || _b === void 0 ? void 0 : _b.toLowerCase) === null || _c === void 0 ? void 0 : _c.call(_b));
519
- return !!isWhitelisted;
520
- });
521
- const t0 = Date.now();
522
- for (const log of filtered) {
523
- (0, logs_decode_shared_1.normalizeLog)(log, true);
524
- }
525
- const transformBatchFn = transformLog.batch || ((logs) => Promise.all(logs.map((log) => transformLog(log))));
526
- const transformedLogs = await transformBatchFn(filtered);
527
- const transformedPair = filtered.map((log, idx) => ({ raw: log, transformed: transformedLogs[idx] }));
528
- const decodeTime = Date.now() - t0;
529
- if (onDecodeStats && filtered.length > 0)
530
- onDecodeStats({ batchSize: filtered.length, decodeTime, itemsDecoded: filtered.length });
531
- if (processor)
532
- await processor(transformedPair.map((i) => i.transformed));
533
- if (options.collect !== false) {
534
- safePush(allLogsPairs, transformedPair);
592
+ const getTopicQueryPages = async function* (topicQuery, offset, fetchAll) {
593
+ const params = {
594
+ addresses: hasAddressFilter ? chunk === null || chunk === void 0 ? void 0 : chunk.join(",") : undefined,
595
+ chainId, from_block: fromBlock, to_block: toBlock,
596
+ ...topicQuery, noTarget,
597
+ };
598
+ const matchesTopics = getTopicMatcher(topicQuery);
599
+ for await (const rows of getIndexerPages(indexerVersion, "/logs", "logs", params, limit, offset, fetchAll, getLogCursor)) {
600
+ yield rows.filter((l) => {
601
+ var _a, _b, _c;
602
+ const isWhitelisted = !addressSet.size || addressSet.has((_c = (_b = ((_a = l.source) !== null && _a !== void 0 ? _a : l.address)) === null || _b === void 0 ? void 0 : _b.toLowerCase) === null || _c === void 0 ? void 0 : _c.call(_b));
603
+ return !!isWhitelisted && matchesTopics(l);
604
+ });
535
605
  }
606
+ };
607
+ if (topicQueries.length === 1) {
608
+ for await (const rows of getTopicQueryPages(topicQueries[0], initialOffset, all))
609
+ await processLogs(rows);
610
+ continue;
536
611
  }
612
+ // OR'd topic queries are fetched in parallel and merged into block order before offset/limit
613
+ // apply, so each query needs at most offset + limit rows; the merged rows are then decoded
614
+ // and processed in page-sized batches
615
+ const maxRows = all ? Infinity : initialOffset + limit;
616
+ const limitTopicQuery = (0, p_limit_1.default)(TOPIC_QUERY_CONCURRENCY);
617
+ const rowsByQuery = await Promise.all(topicQueries.map((topicQuery) => limitTopicQuery(async () => {
618
+ const queryRows = [];
619
+ for await (const rows of getTopicQueryPages(topicQuery, 0, true)) {
620
+ safePush(queryRows, rows);
621
+ if (queryRows.length >= maxRows)
622
+ break;
623
+ }
624
+ return queryRows;
625
+ })));
626
+ const merged = rowsByQuery.flat().sort(compareLogRows).slice(initialOffset, maxRows);
627
+ for (const rows of (0, _1.sliceIntoChunks)(merged, Math.max(limit, 1)))
628
+ await processLogs(rows);
537
629
  }
538
630
  if (debugMode) {
539
631
  console.timeEnd(debugTimeKey);
@@ -2,13 +2,14 @@ import { EventLog, Interface } from "ethers";
2
2
  import { Address } from "../types";
3
3
  import { IndexerGetLogsOptions } from "./indexer";
4
4
  export declare function getBufferedToBlock(toBlock: number, head?: number, buffer?: number): number;
5
+ export type GetLogsTopics = (string | string[] | null)[];
5
6
  export type GetLogsOptions = {
6
7
  target?: Address;
7
8
  topic?: string;
8
9
  keys?: string[];
9
10
  fromBlock?: number;
10
11
  toBlock?: number;
11
- topics?: (string | null)[];
12
+ topics?: GetLogsTopics;
12
13
  extraTopics?: string[];
13
14
  chain?: string;
14
15
  eventAbi?: string | any;
@@ -50,7 +51,7 @@ type GetLogsParamsResponse = {
50
51
  topic: string;
51
52
  iface?: Interface;
52
53
  transformLog: (log: any) => any;
53
- topics?: (string | null)[];
54
+ topics?: GetLogsTopics;
54
55
  topic1?: string;
55
56
  topic2?: string;
56
57
  topic3?: string;
@@ -271,8 +271,28 @@ function trimCachesForStorage(caches, maxLogs = 200000) {
271
271
  const clone = { logs: c.logs, metadata: JSON.parse(JSON.stringify(c.metadata)) };
272
272
  if (c.logs.length > maxLogs) {
273
273
  const sorted = [...c.logs].sort((a, b) => b.blockNumber - a.blockNumber);
274
- clone.logs = sorted.slice(0, maxLogs);
275
- clone.metadata.fromBlock = clone.logs[clone.logs.length - 1].blockNumber;
274
+ let kept = sorted.slice(0, maxLogs);
275
+ const oldestKept = kept[kept.length - 1].blockNumber;
276
+ const heldInOldest = sorted.filter((i) => i.blockNumber === oldestKept).length;
277
+ const keptInOldest = kept.filter((i) => i.blockNumber === oldestKept).length;
278
+ if (heldInOldest === keptInOldest) {
279
+ clone.metadata.fromBlock = oldestKept;
280
+ }
281
+ else {
282
+ // the cut landed inside oldestKept, so drop it: claiming to cover a block we only hold part
283
+ // of would make every later read of this range silently under-report that block
284
+ const whole = kept.filter((i) => i.blockNumber > oldestKept);
285
+ if (whole.length) {
286
+ kept = whole;
287
+ clone.metadata.fromBlock = oldestKept + 1;
288
+ }
289
+ else {
290
+ // the budget does not stretch to one block, keep that block whole rather than lie about it
291
+ kept = sorted.filter((i) => i.blockNumber === oldestKept);
292
+ clone.metadata.fromBlock = oldestKept;
293
+ }
294
+ }
295
+ clone.logs = kept;
276
296
  }
277
297
  return clone;
278
298
  });
@@ -1,4 +1,7 @@
1
- export declare function storeR2JSONString(filename: string, body: string | Buffer): Promise<any>;
2
- export declare function getR2JSONString(filename: string, { throwErrorOnFail }?: {
3
- throwErrorOnFail?: boolean | undefined;
4
- }): Promise<any>;
1
+ export type R2Options = {
2
+ private?: boolean;
3
+ };
4
+ export declare function storeR2JSONString(filename: string, body: string | Buffer, { private: isPrivate }?: R2Options): Promise<any>;
5
+ export declare function getR2JSONString(filename: string, { throwErrorOnFail, private: isPrivate }?: {
6
+ throwErrorOnFail?: boolean;
7
+ } & R2Options): Promise<any>;
package/build/util/r2.js CHANGED
@@ -1,45 +1,104 @@
1
1
  "use strict";
2
+ var _a, _b, _c, _d;
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.storeR2JSONString = storeR2JSONString;
4
5
  exports.getR2JSONString = getR2JSONString;
5
6
  const env_1 = require("./env");
6
7
  const common_1 = require("./common");
8
+ const debugLog_1 = require("./debugLog");
7
9
  const { S3Client, PutObjectCommand, GetObjectCommand, } = require("@aws-sdk/client-s3");
8
- const { R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY } = env_1.ENV_CONSTANTS;
10
+ const { R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_CONFIG } = env_1.ENV_CONSTANTS;
9
11
  const datasetBucket = "defillama-datasets";
12
+ const privateDatasetBucket = "defillama-datasets-private";
10
13
  const publicBucketUrl = "https://defillama-datasets.llama.fi";
11
- let R2;
12
- if (R2_ENDPOINT && R2_ACCESS_KEY_ID && R2_SECRET_ACCESS_KEY) {
13
- R2 = new S3Client({
14
+ function parseR2Config() {
15
+ let config = {};
16
+ if (typeof R2_CONFIG === 'string' && R2_CONFIG.trim().length) {
17
+ try {
18
+ config = JSON.parse(R2_CONFIG);
19
+ }
20
+ catch (e) {
21
+ throw new Error('R2_CONFIG is not valid JSON');
22
+ }
23
+ }
24
+ if (!config.public && R2_ENDPOINT && R2_ACCESS_KEY_ID && R2_SECRET_ACCESS_KEY) {
25
+ config.public = { endpoint: R2_ENDPOINT, accessKeyId: R2_ACCESS_KEY_ID, secretAccessKey: R2_SECRET_ACCESS_KEY };
26
+ }
27
+ return config;
28
+ }
29
+ const r2Config = parseR2Config();
30
+ function createClient(config) {
31
+ if (!config || !config.endpoint || !config.accessKeyId || !config.secretAccessKey)
32
+ return undefined;
33
+ return new S3Client({
14
34
  region: "auto",
15
- endpoint: "https://" + R2_ENDPOINT,
35
+ endpoint: "https://" + config.endpoint.replace(/^https?:\/\//, ''),
16
36
  credentials: {
17
- accessKeyId: R2_ACCESS_KEY_ID,
18
- secretAccessKey: R2_SECRET_ACCESS_KEY,
37
+ accessKeyId: config.accessKeyId,
38
+ secretAccessKey: config.secretAccessKey,
19
39
  },
20
40
  });
21
41
  }
42
+ const R2 = createClient(r2Config.public);
43
+ const R2Private = createClient(r2Config.private);
44
+ const publicBucket = (_b = (_a = r2Config.public) === null || _a === void 0 ? void 0 : _a.bucket) !== null && _b !== void 0 ? _b : datasetBucket;
45
+ const privateBucket = (_d = (_c = r2Config.private) === null || _c === void 0 ? void 0 : _c.bucket) !== null && _d !== void 0 ? _d : privateDatasetBucket;
46
+ function getClient(isPrivate) {
47
+ return isPrivate ? { client: R2Private, bucket: privateBucket } : { client: R2, bucket: publicBucket };
48
+ }
22
49
  const getKey = (filename) => filename.replace(/(:|'|#)/g, '/');
23
- async function storeR2JSONString(filename, body) {
50
+ async function storeR2JSONString(filename, body, { private: isPrivate = false } = {}) {
24
51
  if (typeof body !== 'string')
25
52
  body = body.toString('base64');
26
- if (!R2)
53
+ const { client, bucket } = getClient(isPrivate);
54
+ if (!client)
27
55
  return;
28
56
  const command = new PutObjectCommand({
29
- Bucket: datasetBucket,
57
+ Bucket: bucket,
30
58
  Key: getKey(filename),
31
59
  Body: body,
32
60
  ContentType: "application/json",
33
61
  });
34
- return R2.send(command);
62
+ return client.send(command);
63
+ }
64
+ function isMissingKeyError(e) {
65
+ var _a, _b;
66
+ const name = (_a = e === null || e === void 0 ? void 0 : e.name) !== null && _a !== void 0 ? _a : e === null || e === void 0 ? void 0 : e.Code;
67
+ return name === 'NoSuchKey' || name === 'NotFound' || ((_b = e === null || e === void 0 ? void 0 : e.$metadata) === null || _b === void 0 ? void 0 : _b.httpStatusCode) === 404;
68
+ }
69
+ async function getFromBucket(filename, isPrivate) {
70
+ const { client, bucket } = getClient(isPrivate);
71
+ const command = new GetObjectCommand({ Bucket: bucket, Key: getKey(filename), });
72
+ const { Body } = await client.send(command);
73
+ return Body.transformToString();
35
74
  }
36
- async function getR2JSONString(filename, { throwErrorOnFail = false } = {}) {
75
+ async function getR2JSONString(filename, { throwErrorOnFail = false, private: isPrivate = false } = {}) {
37
76
  try {
38
- if (!R2)
77
+ const { client } = getClient(isPrivate);
78
+ if (!client) {
79
+ if (isPrivate)
80
+ throw new Error('Private R2 bucket is not configured, set R2_CONFIG.private');
39
81
  return await _fetchData();
40
- const command = new GetObjectCommand({ Bucket: datasetBucket, Key: getKey(filename), });
41
- const { Body } = await R2.send(command);
42
- return await Body.transformToString();
82
+ }
83
+ if (!isPrivate)
84
+ return await getFromBucket(filename, false);
85
+ try {
86
+ return await getFromBucket(filename, true);
87
+ }
88
+ catch (e) {
89
+ if (!isMissingKeyError(e))
90
+ throw e;
91
+ // missing in the private bucket: fall back to the public copy and seed the private bucket with it
92
+ const data = R2 ? await getFromBucket(filename, false) : await _fetchData();
93
+ const body = typeof data === 'string' ? data : JSON.stringify(data);
94
+ try {
95
+ await storeR2JSONString(filename, body, { private: true });
96
+ }
97
+ catch (copyError) {
98
+ (0, debugLog_1.debugLog)('Failed to copy', filename, 'from public to private R2 bucket:', copyError);
99
+ }
100
+ return data;
101
+ }
43
102
  }
44
103
  catch (e) {
45
104
  if (throwErrorOnFail)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defillama/sdk",
3
- "version": "5.0.244",
3
+ "version": "5.0.246",
4
4
  "description": "SDK for calculating TVL",
5
5
  "main": "build/index.js",
6
6
  "scripts": {