Skip to content

Commit

Permalink
retryWithBackoff: (#789)
Browse files Browse the repository at this point in the history
  • Loading branch information
bryzettler authored Aug 9, 2024
1 parent 1b1b48e commit 4c90e38
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/hooks/useDerivationAccounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Buffer } from 'buffer'
import * as ed25519 from 'ed25519-hd-key'
import { useEffect, useMemo, useState } from 'react'
import Config from 'react-native-config'
import { retryWithBackoff } from '@utils/retryWithBackoff'
import { useSolana } from '../solana/SolanaProvider'

export const solanaDerivation = (account = -1, change: number | undefined) => {
Expand Down Expand Up @@ -129,16 +130,25 @@ export const useDerivationAccounts = ({ mnemonic }: { mnemonic?: string }) => {
if (keypair) {
let needsMigrated = false
const [balance, tokens, nfts] = await Promise.all([
connection.getBalance(keypair.publicKey),
connection.getTokenAccountsByOwner(keypair.publicKey, {
programId: TOKEN_PROGRAM_ID,
}),
getAssetsByOwner(
connection.rpcEndpoint,
keypair.publicKey.toBase58(),
{
limit: 10,
},
retryWithBackoff(() =>
connection.getBalance(keypair.publicKey),
),
retryWithBackoff(() =>
connection.getTokenAccountsByOwner(
keypair.publicKey,
{
programId: TOKEN_PROGRAM_ID,
},
),
),
retryWithBackoff(() =>
getAssetsByOwner(
connection.rpcEndpoint,
keypair.publicKey.toBase58(),
{
limit: 10,
},
),
),
])

Expand Down
17 changes: 17 additions & 0 deletions src/utils/retryWithBackoff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const retryWithBackoff = async <T>(
fn: () => Promise<T>,
retries = 5,
delay = 1000,
): Promise<T> => {
try {
return await fn()
} catch (error: any) {
if (retries > 0 && error.status === 429) {
// Check for 429 status code
// console.warn(`Rate limit hit, retrying in ${delay}ms...`)
await new Promise((resolve) => setTimeout(resolve, delay))
return retryWithBackoff(fn, retries - 1, delay * 2) // Exponential backoff
}
throw error
}
}

0 comments on commit 4c90e38

Please sign in to comment.