Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/indexer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,60 @@ describe("counter contract", () => {
});
});

test("lagBlocks config option", async () => {
const mockRpcClient = {
...rpcClient,
getLastBlockNumber: vi.fn()
.mockResolvedValueOnce(4n)
.mockResolvedValueOnce(4n)
.mockResolvedValue(4n)
.mockResolvedValue(6n)
};

const indexer = createIndexer({
chain: {
id: 1,
rpcClient: mockRpcClient,
lagBlocks: 2n,
},
contracts: Contracts,
});

indexer.on("Counter:Increment", handleIncrement);
indexer.on("Counter:Decrement", handleDecrement);

indexer.subscribeToContract({
contract: "Counter",
address: "0x0000000000000000000000000000000000000001",
});


let tryTwice: boolean;
indexer.on("progress", ({ currentBlock, targetBlock }) => {
console.log(currentBlock);
console.log(targetBlock);

if (currentBlock == targetBlock && targetBlock == 4n){
if (tryTwice){
indexer.stop();
}
tryTwice = true;
}
});

await new Promise<void>((resolve) => {
indexer.on("stopped", () => {
resolve();
expect(tryTwice).toBe(true);
});

indexer.watch();
});

});



test("resumable index with the same indexer instance", async () => {
const indexer = createIndexer({
chain: {
Expand Down
19 changes: 19 additions & 0 deletions src/indexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export type Config<TAbis extends Record<string, Abi>, TContext = unknown> = {
rpcClient: RpcClient;
pollingIntervalMs?: number;
maxBlockRange?: bigint;
lagBlocks?: bigint; // New field for lag indexing strategy
};
context?: TContext;
logLevel?: keyof typeof LogLevel;
Expand Down Expand Up @@ -176,6 +177,11 @@ export function createIndexer<
// latest is a moving target
if (state.finalTargetBlock === "latest") {
finalTargetBlock = await rpcClient.getLastBlockNumber();

// Apply lag if specified
if (config.chain.lagBlocks) {
finalTargetBlock = applyLag(finalTargetBlock);
}
} else {
finalTargetBlock = state.finalTargetBlock;
}
Expand Down Expand Up @@ -464,6 +470,14 @@ export function createIndexer<
}
}

// Helper function to apply lag
function applyLag(blockNumber: bigint): bigint {
if (config.chain.lagBlocks && blockNumber > BigInt(config.chain.lagBlocks)) {
return blockNumber - BigInt(config.chain.lagBlocks);
}
return 0n;
}

return Object.setPrototypeOf(
{
context: config.context,
Expand Down Expand Up @@ -524,6 +538,11 @@ export function createIndexer<

if (target === "latest") {
targetBlock = await rpcClient.getLastBlockNumber();

// Apply lag if specified
if (config.chain.lagBlocks) {
targetBlock = applyLag(targetBlock);
}
} else {
targetBlock = target;
}
Expand Down