Skip to content

Commit

Permalink
fix: add retry logic to handle 429s (#84)
Browse files Browse the repository at this point in the history
  • Loading branch information
mds1 authored Sep 14, 2024
1 parent bdc98e3 commit 00a368b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
36 changes: 36 additions & 0 deletions script/checks/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { sleep } from 'bun';
import type { PublicClient } from 'viem';

async function retryOnRateLimit<T>(
fn: () => Promise<T>,
maxRetries = 5,
initialDelay = 1000,
): Promise<T> {
let retries = 0;
while (retries < maxRetries) {
try {
return await fn();
} catch (error) {
if (error instanceof Error && error.message.includes('429') && retries < maxRetries) {
const delay = initialDelay * 2 ** retries;
await sleep(delay);
retries++;
} else {
throw error;
}
}
}
throw new Error('Max retries reached');
}

export function createRetryClient(client: PublicClient): PublicClient {
return new Proxy(client, {
get(target, prop, receiver) {
const originalMethod = Reflect.get(target, prop, receiver);
if (typeof originalMethod === 'function') {
return (...args: unknown[]) => retryOnRateLimit(() => originalMethod.apply(target, args));
}
return originalMethod;
},
});
}
3 changes: 2 additions & 1 deletion script/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from './checks/evm-stack-addresses';
import { checkOpcodes } from './checks/opcodes';
import { checkPrecompiles } from './checks/precompiles';
import { createRetryClient } from './checks/utils';
import type { Metadata } from './types';
import { join } from 'node:path';

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

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

0 comments on commit 00a368b

Please sign in to comment.