|
1 | 1 | import { EthBlockhashInfo } from '@lit-protocol/types'; |
2 | 2 |
|
| 3 | +const RETRY_ATTEMPTS = 2; // total attempts = RETRY_ATTEMPTS + 1 |
| 4 | +const RETRY_DELAY_MS = 250; |
| 5 | + |
| 6 | +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 7 | + |
3 | 8 | export const fetchBlockchainData = async () => { |
4 | | - try { |
5 | | - const resp = await fetch( |
6 | | - 'https://block-indexer.litgateway.com/get_most_recent_valid_block' |
7 | | - ); |
8 | | - if (!resp.ok) { |
9 | | - throw new Error(`Primary fetch failed with status: ${resp.status}`); // Or a custom error |
10 | | - } |
| 9 | + let lastError: Error | undefined; |
11 | 10 |
|
12 | | - const blockHashBody: EthBlockhashInfo = await resp.json(); |
13 | | - const { blockhash, timestamp } = blockHashBody; |
| 11 | + for (let attempt = 0; attempt <= RETRY_ATTEMPTS; attempt++) { |
| 12 | + try { |
| 13 | + const resp = await fetch( |
| 14 | + 'https://block-indexer.litgateway.com/get_most_recent_valid_block' |
| 15 | + ); |
| 16 | + if (!resp.ok) { |
| 17 | + throw new Error(`Primary fetch failed with status: ${resp.status}`); |
| 18 | + } |
14 | 19 |
|
15 | | - if (!blockhash || !timestamp) { |
16 | | - throw new Error('Invalid data from primary blockhash source'); |
17 | | - } |
| 20 | + const blockHashBody: EthBlockhashInfo = await resp.json(); |
| 21 | + const { blockhash, timestamp } = blockHashBody; |
18 | 22 |
|
19 | | - return blockhash; |
20 | | - } catch (error) { |
21 | | - if (error instanceof Error) { |
22 | | - throw new Error(error.message); |
| 23 | + if (!blockhash || !timestamp) { |
| 24 | + throw new Error('Invalid data from primary blockhash source'); |
| 25 | + } |
| 26 | + |
| 27 | + return blockhash; |
| 28 | + } catch (error) { |
| 29 | + lastError = error instanceof Error ? error : new Error(String(error)); |
| 30 | + if (attempt === RETRY_ATTEMPTS) { |
| 31 | + throw new Error(lastError.message); |
| 32 | + } |
| 33 | + |
| 34 | + await delay(RETRY_DELAY_MS * (attempt + 1)); |
23 | 35 | } |
24 | | - throw new Error(String(error)); |
25 | 36 | } |
| 37 | + |
| 38 | + throw new Error(lastError?.message ?? 'Unknown fetchBlockchainData error'); |
26 | 39 | }; |
0 commit comments