Skip to content

Commit c0ba675

Browse files
authored
Remove setInterval in blockfinder (#875)
* Remove setInterval in blockfinder * delete cachekey if expired * Add few test cases * Fix expire time * Add comment
1 parent a99c3ab commit c0ba675

File tree

2 files changed

+43
-5
lines changed

2 files changed

+43
-5
lines changed

src/utils/blockfinder.ts

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,28 @@
11
import { subgraphRequest } from '../utils';
22

3-
let cache = {};
3+
let cache: Record<string, any> = {};
4+
let expirationTime = 0;
5+
46
export async function getSnapshots(network, snapshot, provider, networks) {
5-
const cacheKey = `${network}-${snapshot}-${networks.join('-')}`;
6-
if (cache[cacheKey]) return cache[cacheKey];
7+
// If snapshot is latest, return all latest
78
const snapshots = {};
89
networks.forEach((n) => (snapshots[n] = 'latest'));
910
if (snapshot === 'latest') return snapshots;
11+
12+
// Check if cache is valid
13+
const cacheKey = `${network}-${snapshot}-${networks.join('-')}`;
14+
const cachedEntry = cache[cacheKey];
15+
const now = Date.now();
16+
if (cachedEntry && expirationTime > now) {
17+
return cachedEntry;
18+
}
19+
// Reset cache every hour
20+
if (expirationTime < now) {
21+
cache = {};
22+
// Set expiration time to next hour
23+
expirationTime = now + 60 * 60 * 1000 - (now % (60 * 60 * 1000));
24+
}
25+
1026
snapshots[network] = snapshot;
1127
const networkIn = Object.keys(snapshots).filter((s) => network !== s);
1228
if (networkIn.length === 0) return snapshots;
@@ -29,5 +45,3 @@ export async function getSnapshots(network, snapshot, provider, networks) {
2945
cache[cacheKey] = snapshots;
3046
return snapshots;
3147
}
32-
33-
setInterval(() => (cache = {}), 1000 * 60 * 60 * 1); // Clear cache every 1 hour

test/e2e/utils/blockfinder.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { test, expect, describe } from 'vitest';
2+
import { getSnapshots } from '../../../src/utils/blockfinder';
3+
import getProvider from '../../../src/utils/provider';
4+
5+
describe('Test block finder', () => {
6+
const provider = getProvider('1');
7+
test('getSnapshots should work without errors and return object', async () => {
8+
expect(
9+
await getSnapshots('1', 17789783, provider, ['5', '137'])
10+
).toMatchObject({
11+
'1': 17789783,
12+
'137': 45609596,
13+
'5': 9421169
14+
});
15+
});
16+
test('getSnapshots should return all latest if snapshot is latest', async () => {
17+
expect(
18+
await getSnapshots('1', 'latest', provider, ['5', '137'])
19+
).toMatchObject({
20+
'137': 'latest',
21+
'5': 'latest'
22+
});
23+
});
24+
});

0 commit comments

Comments
 (0)