Commit 081ae15a authored by Moody Salem's avatar Moody Salem

retry failed requests up to 3 times

parent f5a5c5e7
......@@ -5,6 +5,7 @@ import { useActiveWeb3React } from '../../hooks'
import { useMulticallContract } from '../../hooks/useContract'
import useDebounce from '../../hooks/useDebounce'
import chunkArray from '../../utils/chunkArray'
import { retry } from '../../utils/retry'
import { useBlockNumber } from '../application/hooks'
import { AppDispatch, AppState } from '../index'
import {
......@@ -142,7 +143,7 @@ export default function Updater() {
)
chunkedCalls.forEach((chunk, index) =>
fetchChunk(multicallContract, chunk, latestBlockNumber)
retry(() => fetchChunk(multicallContract, chunk, latestBlockNumber))
.then(({ results: returnData, blockNumber: fetchBlockNumber }) => {
// accumulates the length of all previous indices
const firstCallKeyIndex = chunkedCalls.slice(0, index).reduce<number>((memo, curr) => memo + curr.length, 0)
......
function wait(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
function waitRandom(min: number, max: number): Promise<void> {
return wait(min + Math.round(Math.random() * (max - min)))
}
/**
* Retries the function that returns the promise until the promise successfully resolves up to n retries
* @param fn function to retry
* @param n how many times to retry
* @param minWait min wait between retries in ms
* @param maxWait max wait between retries in ms
*/
export function retry<T>(
fn: () => Promise<T>,
{ n = 3, minWait = 500, maxWait = 1000 }: { n?: number; minWait?: number; maxWait?: number } = {}
): Promise<T> {
return fn().catch(error => {
if (n === 0) throw error
return waitRandom(minWait, maxWait).then(() => retry(fn, { n: n - 1, minWait, maxWait }))
})
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment