Skip to content

Commit 7a48736

Browse files
committed
fix: Use latest eth_getLogs block as toBlock
1 parent f445632 commit 7a48736

File tree

5 files changed

+50
-55
lines changed

5 files changed

+50
-55
lines changed

src/server/routes/configuration/cors/add.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Static, Type } from "@sinclair/typebox";
22
import { FastifyInstance } from "fastify";
33
import { StatusCodes } from "http-status-codes";
44
import { updateConfiguration } from "../../../../db/configuration/updateConfiguration";
5+
import { dedupeArray } from "../../../../utils/array";
56
import { getConfig } from "../../../../utils/cache/getConfig";
67
import { standardResponseSchema } from "../../../schemas/sharedApiSchemas";
78
import { mandatoryAllowedCorsUrls } from "../../../utils/cors-urls";
@@ -54,12 +55,10 @@ export async function addUrlToCorsConfiguration(fastify: FastifyInstance) {
5455
});
5556

5657
await updateConfiguration({
57-
accessControlAllowOrigin: [
58-
...new Set([
59-
...urlsToAdd,
60-
...oldConfig.accessControlAllowOrigin.split(","),
61-
]),
62-
].join(","),
58+
accessControlAllowOrigin: dedupeArray([
59+
...urlsToAdd,
60+
...oldConfig.accessControlAllowOrigin.split(","),
61+
]).join(","),
6362
});
6463

6564
// Fetch and return the updated configuration

src/server/routes/configuration/cors/remove.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Static, Type } from "@sinclair/typebox";
22
import { FastifyInstance } from "fastify";
33
import { StatusCodes } from "http-status-codes";
44
import { updateConfiguration } from "../../../../db/configuration/updateConfiguration";
5+
import { dedupeArray } from "../../../../utils/array";
56
import { getConfig } from "../../../../utils/cache/getConfig";
67
import { standardResponseSchema } from "../../../schemas/sharedApiSchemas";
78
import { mandatoryAllowedCorsUrls } from "../../../utils/cors-urls";
@@ -61,9 +62,7 @@ export async function removeUrlToCorsConfiguration(fastify: FastifyInstance) {
6162
.filter((url) => !urlsToRemove.includes(url));
6263

6364
await updateConfiguration({
64-
accessControlAllowOrigin: [...new Set([...newAllowOriginsList])].join(
65-
",",
66-
),
65+
accessControlAllowOrigin: dedupeArray(newAllowOriginsList).join(","),
6766
});
6867

6968
// Fetch and return the updated configuration

src/server/routes/configuration/cors/set.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Static, Type } from "@sinclair/typebox";
22
import { FastifyInstance } from "fastify";
33
import { StatusCodes } from "http-status-codes";
44
import { updateConfiguration } from "../../../../db/configuration/updateConfiguration";
5+
import { dedupeArray } from "../../../../utils/array";
56
import { getConfig } from "../../../../utils/cache/getConfig";
67
import { standardResponseSchema } from "../../../schemas/sharedApiSchemas";
78
import { mandatoryAllowedCorsUrls } from "../../../utils/cors-urls";
@@ -44,13 +45,11 @@ export async function setUrlsToCorsConfiguration(fastify: FastifyInstance) {
4445
handler: async (req, res) => {
4546
const urls = req.body.urls.map((url) => url.trim());
4647

47-
// Add required domains and dedupe.
48-
const dedupe = Array.from(
49-
new Set([...urls, ...mandatoryAllowedCorsUrls]),
50-
);
51-
5248
await updateConfiguration({
53-
accessControlAllowOrigin: dedupe.join(","),
49+
accessControlAllowOrigin: dedupeArray([
50+
...urls,
51+
...mandatoryAllowedCorsUrls,
52+
]).join(","),
5453
});
5554

5655
// Fetch and return the updated configuration

src/utils/array.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export const dedupeArray = <T>(array: T[]): T[] => {
2+
return [...new Set(array)];
3+
};

src/worker/tasks/chainIndexer.ts

Lines changed: 35 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { bulkInsertContractEventLogs } from "../../db/contractEventLogs/createCo
88
import { getContractSubscriptionsByChainId } from "../../db/contractSubscriptions/getContractSubscriptions";
99
import { bulkInsertContractTransactionReceipts } from "../../db/contractTransactionReceipts/createContractTransactionReceipts";
1010
import { PrismaTransaction } from "../../schema/prisma";
11+
import { dedupeArray } from "../../utils/array";
1112
import { getContract } from "../../utils/cache/getContract";
1213
import { getSdk } from "../../utils/cache/getSdk";
1314
import { logger } from "../../utils/logger";
@@ -106,9 +107,7 @@ export const getSubscribedContractsLogs = async (
106107
const logs = await ethGetLogs(params);
107108

108109
// cache the contracts and abi
109-
const uniqueContractAddresses = [
110-
...new Set<string>(logs.map((log) => log.address)),
111-
];
110+
const uniqueContractAddresses = dedupeArray(logs.map((log) => log.address));
112111
const contracts = await Promise.all(
113112
uniqueContractAddresses.map(async (address) => {
114113
const contract = await getContract({
@@ -124,9 +123,7 @@ export const getSubscribedContractsLogs = async (
124123
}, {} as Record<string, SmartContract<ethers.BaseContract>>);
125124

126125
// cache the blocks and their timestamps
127-
const uniqueBlockNumbers = [
128-
...new Set<number>(logs.map((log) => log.blockNumber)),
129-
];
126+
const uniqueBlockNumbers = dedupeArray(logs.map((log) => log.blockNumber));
130127
const blockDetails = await Promise.all(
131128
uniqueBlockNumbers.map(async (blockNumber) => ({
132129
blockNumber,
@@ -168,7 +165,9 @@ export const getSubscribedContractsLogs = async (
168165
}
169166
}
170167

171-
const block = blockCache[log.blockNumber];
168+
// Block may be null if the RPC does not yet have block details. Fall back to current time.
169+
const block = blockCache[log.blockNumber] as ethers.providers.Block | null;
170+
const timestamp = block ? new Date(block.timestamp * 1000) : new Date();
172171

173172
// format the log entry
174173
return {
@@ -183,7 +182,7 @@ export const getSubscribedContractsLogs = async (
183182
data: log.data,
184183
eventName: decodedEventName,
185184
decodedLog: decodedLog,
186-
timestamp: new Date(block.timestamp * 1000), // ethers timestamp is s, Date uses ms
185+
timestamp,
187186
transactionIndex: log.transactionIndex,
188187
logIndex: log.logIndex,
189188
};
@@ -285,67 +284,63 @@ export const createChainIndexerTask = async (
285284
}
286285

287286
const sdk = await getSdk({ chainId });
288-
289287
const provider = sdk.getProvider();
290-
const currentBlockNumber = await provider.getBlockNumber();
291288

292-
// check if up-to-date
293-
if (lastIndexedBlock >= currentBlockNumber) {
289+
// Get latest block with logs. This should be the maxBlock to query up to.
290+
const logs = await provider.getLogs({ fromBlock: "latest" });
291+
if (logs.length === 0) {
294292
return;
295293
}
294+
const currentBlockNumber = logs[0].blockNumber;
296295

297-
// limit max block numbers
298-
let toBlockNumber = currentBlockNumber;
299-
if (currentBlockNumber - (lastIndexedBlock + 1) > maxBlocksToIndex) {
300-
toBlockNumber = lastIndexedBlock + 1 + maxBlocksToIndex;
296+
// Check if up-to-date.
297+
if (lastIndexedBlock >= currentBlockNumber) {
298+
return;
301299
}
302300

301+
// Limit max block number.
302+
const toBlockNumber = Math.min(
303+
currentBlockNumber,
304+
lastIndexedBlock + maxBlocksToIndex,
305+
);
306+
303307
const subscribedContracts = await getContractSubscriptionsByChainId(
304308
chainId,
305309
);
306-
const subscribedContractAddresses = [
307-
...new Set<string>(
308-
subscribedContracts.map(
309-
(subscribedContract) => subscribedContract.contractAddress,
310-
),
310+
const subscribedContractAddresses = dedupeArray(
311+
subscribedContracts.map(
312+
(subscribedContract) => subscribedContract.contractAddress,
311313
),
312-
];
314+
);
313315

314316
await Promise.all([
317+
// Checks eth_getLogs.
315318
indexContractEvents({
316319
pgtx,
317320
chainId,
318-
fromBlockNumber: lastIndexedBlock + 1,
321+
fromBlockNumber: lastIndexedBlock,
319322
toBlockNumber,
320323
subscribedContractAddresses,
321324
}),
325+
// Checks eth_getBlockByNumber.
322326
indexTransactionReceipts({
323327
pgtx,
324328
chainId,
325-
fromBlockNumber: lastIndexedBlock + 1,
329+
fromBlockNumber: lastIndexedBlock,
326330
toBlockNumber,
327331
subscribedContractAddresses,
328332
}),
329333
]);
330334

331-
// update the block number
332-
try {
333-
await upsertChainIndexer({
334-
pgtx,
335-
chainId,
336-
currentBlockNumber: toBlockNumber, // last indexed block
337-
});
338-
} catch (error) {
339-
logger({
340-
service: "worker",
341-
level: "error",
342-
message: `Failed to update latest block number - Chain Indexer: ${chainId}`,
343-
error: error,
344-
});
345-
}
335+
// Update the last processed block number.
336+
await upsertChainIndexer({
337+
pgtx,
338+
chainId,
339+
currentBlockNumber: toBlockNumber,
340+
});
346341
},
347342
{
348-
timeout: 5 * 60000, // 3 minutes timeout
343+
timeout: 5 * 60 * 1000,
349344
},
350345
);
351346
} catch (err: any) {

0 commit comments

Comments
 (0)