@defillama/sdk 5.0.245 → 5.0.249

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.
@@ -97,20 +97,20 @@ class LlamaProvider extends ethers_1.FallbackProvider {
97
97
  await this._isReady;
98
98
  let runners = [...this.rpcs];
99
99
  if (method === 'getLogs') {
100
- runners = [...this.archivalRPCs];
101
- this.rpcs.filter(i => !runners.map(i => i.url).includes(i.url)).forEach(i => runners.push(i)); // ensure that there are no duplicates
102
- runners = runners.filter(i => !i.url.includes('llamarpc.com'));
100
+ // archival RPCs first, then the remaining regular RPCs, each URL once
101
+ const seen = new Set();
102
+ runners = [...this.archivalRPCs, ...this.rpcs].filter(i => {
103
+ if (i.url.includes('llamarpc.com') || seen.has(i.url))
104
+ return false;
105
+ seen.add(i.url);
106
+ return true;
107
+ });
103
108
  }
104
109
  if (!runners.length)
105
110
  throw new Error('No RPCs available for ' + this.chainName);
106
111
  let primaryRunner = runners[0];
107
112
  let errors = [];
108
- if (method === 'getLogs') {
109
- runners = runners.slice(1).concat(this.rpcs);
110
- runners = runners.sort(() => Math.random() - 0.5); // randomize order of runners
111
- }
112
- else
113
- runners = runners.slice(1).sort(() => Math.random() - 0.5); // randomize order of runners
113
+ runners = runners.slice(1).sort(() => Math.random() - 0.5); // randomize order of runners
114
114
  const isArchivalRequest = ['call', 'getBalance'].includes(method) && params[1] !== 'latest';
115
115
  // check if domain name of primaryRunner.url is llama
116
116
  const isLlamaRPC = primaryRunner.url.includes('llama');
@@ -329,7 +329,7 @@ const httpRPC = {
329
329
  };
330
330
  function getMedianBlockValue(blocks) {
331
331
  blocks.sort((a, b) => a - b);
332
- const mid = Math.floor(blocks.length / 3);
332
+ const mid = Math.floor(blocks.length / 2);
333
333
  return blocks.length % 2 !== 0 ? blocks[mid] : (blocks[mid - 1] + blocks[mid]) / 2;
334
334
  }
335
335
  let lastPrintTimeMS = Date.now();
@@ -4,12 +4,14 @@ interface WriteCacheOptions {
4
4
  skipR2CacheWrite?: boolean;
5
5
  alreadyCompressed?: boolean;
6
6
  skipCompression?: boolean;
7
+ private?: boolean;
7
8
  }
8
9
  interface ReadCacheOptions {
9
10
  checkIfRecent?: boolean;
10
11
  readFromR2Cache?: boolean;
11
12
  skipR2Cache?: boolean;
12
13
  skipCompression?: boolean;
14
+ private?: boolean;
13
15
  }
14
16
  export declare function writeCache(file: string, data: any, options?: WriteCacheOptions): Promise<string | undefined>;
15
17
  export declare function parseCache(dataString: string | Buffer, options?: ReadCacheOptions): Promise<any>;
@@ -91,7 +91,7 @@ async function readCache(file, options = {}) {
91
91
  if (options.skipR2Cache)
92
92
  return;
93
93
  try {
94
- const r2Data = await (0, r2_1.getR2JSONString)(exports.currentVersion + '/' + file, { throwErrorOnFail: (_a = options.readFromR2Cache) !== null && _a !== void 0 ? _a : false });
94
+ const r2Data = await (0, r2_1.getR2JSONString)(exports.currentVersion + '/' + file, { throwErrorOnFail: (_a = options.readFromR2Cache) !== null && _a !== void 0 ? _a : false, private: options.private });
95
95
  if (r2Data) {
96
96
  // `file` already carries the `-uncompressed` suffix (added above), so omit skipCompression here to avoid writeCache appending it again
97
97
  await writeCache(file, r2Data, { alreadyCompressed: true, skipR2CacheWrite: true });
@@ -126,7 +126,7 @@ async function writeCache(file, data, options = {}) {
126
126
  await createSubPath(path.dirname(filePath));
127
127
  await fs.writeFile(filePath, fileData);
128
128
  if (!options.skipR2CacheWrite) {
129
- await (0, r2_1.storeR2JSONString)(exports.currentVersion + '/' + file, fileData);
129
+ await (0, r2_1.storeR2JSONString)(exports.currentVersion + '/' + file, fileData, { private: options.private });
130
130
  }
131
131
  return fileData;
132
132
  }
@@ -498,6 +498,7 @@
498
498
  "saga": "Saga",
499
499
  "sanko": "Sanko",
500
500
  "sapphire": "Oasis Sapphire",
501
+ "saseul": "SASEUL",
501
502
  "satori": "Satori",
502
503
  "scroll": "Scroll",
503
504
  "secret": "Secret",
@@ -627,7 +628,7 @@
627
628
  "zenrock": "Zenrock",
628
629
  "zero_network": "Zero Network",
629
630
  "zeta": "ZetaChain",
630
- "zigchain": "ZIGChain",
631
+ "zigchain": "ZIG Chain",
631
632
  "zilliqa": "Zilliqa",
632
633
  "zircuit": "Zircuit",
633
634
  "zkfair": "Zkfair",
@@ -1156,6 +1157,7 @@
1156
1157
  "Ronin": "ronin",
1157
1158
  "Rootstock": "rsk",
1158
1159
  "Rubin": "rubin",
1160
+ "SASEUL": "saseul",
1159
1161
  "SELEMAN": "seleman",
1160
1162
  "SGE": "sge",
1161
1163
  "SKALE": "skale",
@@ -1291,6 +1293,7 @@
1291
1293
  "Xone Chain": "xone",
1292
1294
  "Xphere": "xp",
1293
1295
  "Yominet": "yomi",
1296
+ "ZIG Chain": "zigchain",
1294
1297
  "ZIGChain": "zigchain",
1295
1298
  "ZKsync Era": "era",
1296
1299
  "ZKsync Lite": "zksync",
@@ -1327,10 +1330,12 @@
1327
1330
  },
1328
1331
  "deadChains": {
1329
1332
  "airdao": "2026-01-20",
1333
+ "alv": "2026-10-27",
1330
1334
  "ancient8": "2026-06-19",
1331
1335
  "artela": "2026-06-05",
1332
1336
  "astrzk": "2026-02-12",
1333
1337
  "bitrock": "2026-02-12",
1338
+ "blast": "2026-10-26",
1334
1339
  "boba_bnb": "2026-01-20",
1335
1340
  "bouncebit": "2026-08-24",
1336
1341
  "btnx": "2026-07-09",
@@ -1372,6 +1377,7 @@
1372
1377
  "genesys": "2026-03-01",
1373
1378
  "godwoken": "2026-01-06",
1374
1379
  "godwoken_v1": "2026-01-06",
1380
+ "gravity": "2026-11-01",
1375
1381
  "grove": "2025-07-28",
1376
1382
  "ham": "2026-06-05",
1377
1383
  "harmony": "2026-09-09",
@@ -1391,6 +1397,7 @@
1391
1397
  "kopi": "2026-05-16",
1392
1398
  "kroma": "2026-01-20",
1393
1399
  "kujira": "2026-08-03",
1400
+ "lisk": "2026-11-02",
1394
1401
  "loop": "2026-08-03",
1395
1402
  "manta_atlantic": "2026-08-01",
1396
1403
  "migaloo": "2026-02-12",
@@ -1409,6 +1416,7 @@
1409
1416
  "nova": "2026-08-03",
1410
1417
  "nuls": "2026-03-25",
1411
1418
  "odyssey": "2026-09-02",
1419
+ "okexchain": "2026-01-01",
1412
1420
  "onus": "2026-06-05",
1413
1421
  "pacaswap": "2026-10-01",
1414
1422
  "palm": "2026-10-13",
@@ -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");
@@ -20,21 +22,21 @@ function getClient() {
20
22
  if (!envString)
21
23
  return;
22
24
  config = JSON.parse(envString.replace(/\\"/g, '"')); // replace escaped quotes
25
+ if (!_client)
26
+ _client = new elasticsearch_1.Client({
27
+ maxRetries: 3,
28
+ requestTimeout: 5000,
29
+ compression: true,
30
+ node: config.host,
31
+ auth: {
32
+ username: config.username,
33
+ password: config.password,
34
+ },
35
+ });
23
36
  }
24
37
  catch (error) {
25
38
  return;
26
39
  }
27
- if (!_client)
28
- _client = new elasticsearch_1.Client({
29
- maxRetries: 3,
30
- requestTimeout: 5000,
31
- compression: true,
32
- node: config.host,
33
- auth: {
34
- username: config.username,
35
- password: config.password,
36
- },
37
- });
38
40
  return _client;
39
41
  }
40
42
  async function writeLog(index, log) {
@@ -111,3 +113,23 @@ 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 timestamp = +Date.now();
126
+ const docs = issues
127
+ .map(({ value, baseline, ...issue }) => ({ ...issue, value, baseline, timestamp, deviation: value != null && baseline ? (value - baseline) / baseline : null }));
128
+ if (!docs.length)
129
+ return;
130
+ const write = client.bulk({ index: addYearAndMonth('data-issues'), operations: docs.flatMap((doc) => [{ index: {} }, doc]), timeout: `${limitMs}ms` })
131
+ .then((res) => { if (res.errors)
132
+ console.error('data-issues bulk write: some items failed'); })
133
+ .catch((e) => console.error('data-issues write failed:', e === null || e === void 0 ? void 0 : e.message));
134
+ 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); })]);
135
+ }
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
  };
@@ -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);
@@ -338,7 +367,8 @@ async function getLogs(options) {
338
367
  if (processor && typeof options.collect === "undefined" && clientStreaming) {
339
368
  options = { ...options, collect: false };
340
369
  }
341
- 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);
342
372
  const viemFastPath =
343
373
  // Preserve the historical streaming shape, including entireLog: the viem
344
374
  // fast path exposes args without adding the buffered decoder's parsedLog.
@@ -445,18 +475,29 @@ async function getLogs(options) {
445
475
  safePush(collected, transformedLogs);
446
476
  }
447
477
  };
448
- for (const chunk of addressChunks) {
449
- if (Array.isArray(chunk) && chunk.length === 0)
450
- 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) => {
451
496
  const qs = new URLSearchParams();
452
497
  qs.set("chainId", String(chainId));
453
- qs.set("topic0", topic);
454
- if (topic1)
455
- qs.set("topic1", topic1);
456
- if (topic2)
457
- qs.set("topic2", topic2);
458
- if (topic3)
459
- qs.set("topic3", topic3);
498
+ for (const [key, value] of Object.entries(topicQuery))
499
+ qs.set(key, value);
500
+ const matchesTopics = getTopicMatcher(topicQuery);
460
501
  if (fromBlock != null)
461
502
  qs.set("from_block", String(fromBlock));
462
503
  if (toBlock != null)
@@ -467,7 +508,6 @@ async function getLogs(options) {
467
508
  qs.set("noTarget", "true");
468
509
  qs.set("limit", "all");
469
510
  qs.set("offset", "0");
470
- const transformBatch = [];
471
511
  let stopNow = false;
472
512
  await streamLogs({
473
513
  path: `/logs?${qs.toString()}`,
@@ -480,28 +520,34 @@ async function getLogs(options) {
480
520
  if (indexerVersion === "v4")
481
521
  (0, indexer_compatibility_1.normalizeV4Row)(raw, "logs");
482
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));
483
- if (!okAddress)
484
- return;
485
- if (remainingOffset > 0) {
486
- remainingOffset--;
487
- return;
488
- }
489
- if (remainingLimit <= 0) {
523
+ if (okAddress && matchesTopics(raw) && !(await onRow(raw)))
490
524
  stopNow = true;
491
- return;
492
- }
493
- transformBatch.push(raw);
494
- remainingLimit--;
495
- if (remainingLimit <= 0)
496
- stopNow = true;
497
- if (transformBatch.length >= MICRO_BATCH_SIZE) {
498
- const batch = transformBatch.splice(0, MICRO_BATCH_SIZE);
499
- await flushBatch(batch);
500
- }
501
525
  },
502
526
  shouldStop: () => stopNow,
503
527
  onChunkStats: onWireStats,
504
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
+ }
505
551
  if (transformBatch.length > 0) {
506
552
  await flushBatch(transformBatch.splice(0, transformBatch.length));
507
553
  }
@@ -523,36 +569,63 @@ async function getLogs(options) {
523
569
  (0, debugLog_1.debugLog)("[Indexer] Pulling logs " + debugTimeKey);
524
570
  console.time(debugTimeKey);
525
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
+ };
526
589
  for (const chunk of addressChunks) {
527
590
  if (Array.isArray(chunk) && chunk.length === 0)
528
591
  throw new Error("Address chunk cannot be empty");
529
- const params = {
530
- addresses: hasAddressFilter ? chunk === null || chunk === void 0 ? void 0 : chunk.join(",") : undefined,
531
- chainId, topic0: topic, from_block: fromBlock, to_block: toBlock,
532
- topic1, topic2, topic3, noTarget,
533
- };
534
- for await (const rows of getIndexerPages(indexerVersion, "/logs", "logs", params, limit, initialOffset, all, getLogCursor)) {
535
- const filtered = rows.filter((l) => {
536
- var _a, _b, _c;
537
- 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));
538
- return !!isWhitelisted;
539
- });
540
- const t0 = Date.now();
541
- for (const log of filtered) {
542
- (0, logs_decode_shared_1.normalizeLog)(log, true);
543
- }
544
- const transformBatchFn = transformLog.batch || ((logs) => Promise.all(logs.map((log) => transformLog(log))));
545
- const transformedLogs = await transformBatchFn(filtered);
546
- const transformedPair = filtered.map((log, idx) => ({ raw: log, transformed: transformedLogs[idx] }));
547
- const decodeTime = Date.now() - t0;
548
- if (onDecodeStats && filtered.length > 0)
549
- onDecodeStats({ batchSize: filtered.length, decodeTime, itemsDecoded: filtered.length });
550
- if (processor)
551
- await processor(transformedPair.map((i) => i.transformed));
552
- if (options.collect !== false) {
553
- 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
+ });
554
605
  }
606
+ };
607
+ if (topicQueries.length === 1) {
608
+ for await (const rows of getTopicQueryPages(topicQueries[0], initialOffset, all))
609
+ await processLogs(rows);
610
+ continue;
555
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);
556
629
  }
557
630
  if (debugMode) {
558
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>;