Skip to content

Commit 00a368b

Browse files
authored
fix: add retry logic to handle 429s (#84)
1 parent bdc98e3 commit 00a368b

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

script/checks/utils.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { sleep } from 'bun';
2+
import type { PublicClient } from 'viem';
3+
4+
async function retryOnRateLimit<T>(
5+
fn: () => Promise<T>,
6+
maxRetries = 5,
7+
initialDelay = 1000,
8+
): Promise<T> {
9+
let retries = 0;
10+
while (retries < maxRetries) {
11+
try {
12+
return await fn();
13+
} catch (error) {
14+
if (error instanceof Error && error.message.includes('429') && retries < maxRetries) {
15+
const delay = initialDelay * 2 ** retries;
16+
await sleep(delay);
17+
retries++;
18+
} else {
19+
throw error;
20+
}
21+
}
22+
}
23+
throw new Error('Max retries reached');
24+
}
25+
26+
export function createRetryClient(client: PublicClient): PublicClient {
27+
return new Proxy(client, {
28+
get(target, prop, receiver) {
29+
const originalMethod = Reflect.get(target, prop, receiver);
30+
if (typeof originalMethod === 'function') {
31+
return (...args: unknown[]) => retryOnRateLimit(() => originalMethod.apply(target, args));
32+
}
33+
return originalMethod;
34+
},
35+
});
36+
}

script/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
} from './checks/evm-stack-addresses';
88
import { checkOpcodes } from './checks/opcodes';
99
import { checkPrecompiles } from './checks/precompiles';
10+
import { createRetryClient } from './checks/utils';
1011
import type { Metadata } from './types';
1112
import { join } from 'node:path';
1213

@@ -77,7 +78,7 @@ function initClient(rpcUrls: string[]) {
7778
// Websocket seems to hang and script doesn't exit, so we only use HTTP.
7879
const https = rpcUrls.filter((url) => url.startsWith('https')).map((url) => http(url));
7980
const transport = fallback([...https]);
80-
return createPublicClient({ transport });
81+
return createRetryClient(createPublicClient({ transport }));
8182
}
8283

8384
async function getMetadata(chainId: number): Promise<Metadata> {

0 commit comments

Comments
 (0)