Skip to content

Commit 72f0148

Browse files
committed
0.1.9 Upgraded fetchWithRetry
1 parent 37943ff commit 72f0148

2 files changed

Lines changed: 25 additions & 17 deletions

File tree

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "circuitscan",
3-
"version": "0.1.8",
3+
"version": "0.1.9",
44
"main": "cli.js",
55
"type": "module",
66
"author": "numtel <ben@latenightsketches.com>",

src/utils.js

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import {accessSync, readFileSync} from 'node:fs';
22
import {dirname, join, resolve} from 'node:path';
33
import {fileURLToPath} from 'node:url';
4+
import { fetch, Agent } from 'undici';
45

56
import * as chains from 'viem/chains';
67

8+
const agent = new Agent({ connectTimeout: 10000 });
9+
710
export const DEFAULT_CONFIG = 'https://circuitscan.org/cli.json';
811
export const MAX_POST_SIZE = 6 * 1024 ** 2; // 6 MB
912

@@ -124,21 +127,26 @@ export function viemChain(nameOrId) {
124127
}
125128

126129
export async function fetchWithRetry(url, options = {}, retries = 5, delay = 1000) {
127-
for (let attempt = 0; attempt < retries; attempt++) {
128-
try {
129-
const response = await fetch(url, options);
130-
return response;
131-
} catch (error) {
132-
if (error.message.includes('ETIMEDOUT') || error.message.includes('fetch failed')) {
133-
if (attempt < retries - 1) {
134-
console.warn(`Retrying fetch (${attempt + 1}/${retries}) after timeout...`);
135-
await new Promise(res => setTimeout(res, delay * Math.pow(2, attempt))); // Exponential backoff
136-
} else {
137-
throw new Error(`Fetch failed after ${retries} retries: ${error.message}`);
138-
}
139-
} else {
140-
throw error; // If it's not a timeout error, rethrow it immediately
141-
}
142-
}
130+
for (let attempt = 0; attempt < retries; attempt++) {
131+
try {
132+
const response = await fetch(url, { ...options, dispatcher: agent });
133+
return response;
134+
} catch (error) {
135+
const errorCode = error?.cause?.code;
136+
console.error(`Fetch attempt ${attempt + 1} failed:`, errorCode, error.message);
137+
138+
const shouldRetry = errorCode === 'ETIMEDOUT' ||
139+
errorCode === 'ENOTFOUND' ||
140+
error.message.includes('fetch failed');
141+
142+
if (!shouldRetry) throw error;
143+
144+
if (attempt < retries - 1) {
145+
console.warn(`Retrying fetch (${attempt + 1}/${retries}) after error: ${errorCode}`);
146+
await new Promise(res => setTimeout(res, delay * Math.pow(2, attempt))); // Exponential backoff
147+
} else {
148+
throw new Error(`Fetch failed after ${retries} retries: ${error.message}`);
149+
}
143150
}
151+
}
144152
}

0 commit comments

Comments
 (0)