Skip to content

Instantly share code, notes, and snippets.

@NotoriousPyro
Last active April 29, 2024 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NotoriousPyro/127653033cf19d41edc4daec55d71a64 to your computer and use it in GitHub Desktop.
Save NotoriousPyro/127653033cf19d41edc4daec55d71a64 to your computer and use it in GitHub Desktop.
Example TypeScript web3.js with retry fetcher
import * as nodeFetch from 'node-fetch';
import fetch from 'fetch-retry'
import https from 'https';
const _fetch = fetch(nodeFetch.default);
type FetchFn = typeof nodeFetch.default;
export type Fetcher = (...args: Parameters<FetchFn>) => ReturnType<FetchFn>;
export type FetcherWithCustomAgent = (agent: https.Agent) => Fetcher;
export const RetryFetcher: Fetcher = (...args) => {
const [url, init] = args;
return _fetch(url, {
...init,
retries: 3,
retryDelay: 1000,
// eslint-disable-next-line @typescript-eslint/require-await
retryOn: async function (attempt, error, response) {
if (attempt > 3) return false;
if (response?.status === 429) {
return false;
}
if (error) {
return true;
}
return false;
}
});
}
export const FetcherWithCustomAgent: FetcherWithCustomAgent = (agent: https.Agent) => {
const fetcher: Fetcher = (...args) => {
const [url, init] = args;
return RetryFetcher(url, {
...init,
agent
})
}
return fetcher;
}
// example for web3.js
const web3Agent = new https.Agent({
keepAlive: true,
keepAliveMsecs: 60000,
})
const connection = new Connection(
"https://my_sol_endpoint_URL",
{
httpAgent: web3Agent,
...restofRPCsettings,
fetch: RetryFetcher,
},
);
const jupiterAgent = new https.Agent({
keepAlive: true,
keepAliveMsecs: 60000,
})
// example for jupiter v6 client:
export const jupiterOfficial = createJupiterApiClient({
fetchApi: FetcherWithCustomAgent(jupiterAgent),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment