Blockhash not found when sending transaction

When sending a transaction using Solana web3, it sometimes shows this error:
Error: failed to send transaction: Transaction simulation failed: Blockhash not found

What is the proper way of dealing with this error other than retrying for x amount of times?
Is there a way to guarantee this issue won't happen when sending transactions?

Here is an example of how I'm sending a transaction:

const web3 = require("@solana/web3.js")
const bs58 = require('bs58')

const publicKey = new web3.PublicKey(new Uint8Array(bs58.decode("BASE_58_PUBLIC_KEY").toJSON().data))
const secretKey = new Uint8Array(bs58.decode("BASE_58_SECRET_KEY").toJSON().data)

const connection = new web3.Connection(
  "https://api.mainnet-beta.solana.com", "finalized",
  {
    commitment: "finalized",
    confirmTransactionInitialTimeout: 30000
  }
)
const transaction = new web3.Transaction().add(
  web3.SystemProgram.transfer({
    fromPubkey: publicKey,
    toPubkey: publicKey,
    lamports: 1
  })
)
web3.sendAndConfirmTransaction(
  connection,
  transaction,
  [{publicKey: publicKey, secretKey: secretKey}],
  {commitment: "finalized"}
)


How can I improve this to avoid the Blockhash not found error?


Solution 1:

Retrying is not a bad thing! In some situations, it's actually the preferred way to handle dropped transactions.

You may like to read through this cookbook entry about retrying transactions: https://solanacookbook.com/guides/retrying-transactions.html

Specifically, it explains how to implement some retry logic: https://solanacookbook.com/guides/retrying-transactions.html#customizing-rebroadcast-logic

And what retrying means specifically: https://solanacookbook.com/guides/retrying-transactions.html#when-to-re-sign-transactions