diff --git a/src/hooks/useDerivationAccounts.ts b/src/hooks/useDerivationAccounts.ts index 33e35dcc8..c1eb6b5c8 100644 --- a/src/hooks/useDerivationAccounts.ts +++ b/src/hooks/useDerivationAccounts.ts @@ -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) => { @@ -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, + }, + ), ), ]) diff --git a/src/utils/retryWithBackoff.ts b/src/utils/retryWithBackoff.ts new file mode 100644 index 000000000..3a79d56c2 --- /dev/null +++ b/src/utils/retryWithBackoff.ts @@ -0,0 +1,17 @@ +export const retryWithBackoff = async ( + fn: () => Promise, + retries = 5, + delay = 1000, +): Promise => { + 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 + } +}