Last active
April 29, 2024 20:26
-
-
Save NotoriousPyro/127653033cf19d41edc4daec55d71a64 to your computer and use it in GitHub Desktop.
Example TypeScript web3.js with retry fetcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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