|
1 | 1 | import { getCurrentEpoch } from '@/config'; |
2 | 2 | import { fetchR1MintedLastEpoch } from '@/lib/api/blockchain'; |
3 | | -import { cache } from 'react'; |
4 | 3 | import { formatUnits } from 'viem'; |
| 4 | +interface CacheEntry { |
| 5 | + value: string; |
| 6 | + epoch: number; |
| 7 | + timestamp: number; |
| 8 | +} |
5 | 9 |
|
6 | | -let cachedValue: string | null = null; |
7 | | -let cachedEpoch: number | null = null; |
| 10 | +let cacheEntry: CacheEntry | null = null; |
| 11 | +let fetchPromise: Promise<string> | null = null; |
8 | 12 |
|
9 | | -const getCachedR1MintedLastEpoch = cache(async () => { |
| 13 | +const getCachedR1MintedLastEpoch = async (): Promise<string> => { |
10 | 14 | const currentEpoch = getCurrentEpoch(); |
| 15 | + const now = Date.now(); |
| 16 | + |
| 17 | + // Return cached value if still valid |
| 18 | + if (cacheEntry && cacheEntry.epoch === currentEpoch) { |
| 19 | + return cacheEntry.value; |
| 20 | + } |
11 | 21 |
|
12 | | - // Check if we have cached data for the current epoch |
13 | | - if (cachedValue !== null && cachedEpoch === currentEpoch) { |
14 | | - // console.log(`[R1MintedLastEpoch] using cached data for epoch ${currentEpoch}`); |
15 | | - return cachedValue; |
| 22 | + // Prevent multiple concurrent fetches |
| 23 | + if (fetchPromise) { |
| 24 | + return fetchPromise; |
16 | 25 | } |
17 | 26 |
|
18 | | - // console.log(`[R1MintedLastEpoch] fetching new data for epoch ${currentEpoch}`); |
19 | | - const value = await fetchR1MintedLastEpoch(); |
20 | | - const valueString = value.toString(); |
| 27 | + fetchPromise = (async () => { |
| 28 | + try { |
| 29 | + const value = await fetchR1MintedLastEpoch(); |
| 30 | + const valueString = value.toString(); |
21 | 31 |
|
22 | | - // console.log(`[R1MintedLastEpoch] fetched new data for epoch ${currentEpoch}, value: ${valueString}`); |
| 32 | + cacheEntry = { |
| 33 | + value: valueString, |
| 34 | + epoch: currentEpoch, |
| 35 | + timestamp: now, |
| 36 | + }; |
23 | 37 |
|
24 | | - cachedValue = valueString; |
25 | | - cachedEpoch = currentEpoch; |
| 38 | + return valueString; |
| 39 | + } catch (error) { |
| 40 | + console.error('[R1MintedLastEpoch] error', error); |
| 41 | + throw error; |
| 42 | + } finally { |
| 43 | + fetchPromise = null; |
| 44 | + } |
| 45 | + })(); |
26 | 46 |
|
27 | | - return valueString; |
28 | | -}); |
| 47 | + return fetchPromise; |
| 48 | +}; |
29 | 49 |
|
30 | 50 | export default async function R1MintedLastEpoch() { |
31 | 51 | let value: bigint | undefined; |
|
0 commit comments