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?
Retrying is not a bad thing! In some situations, it's actually the preferred way to handle dropped transactions. For example, that means doing:
// assuming you have a transaction named `transaction` already
const blockhashResponse = await connection.getLatestBlockhashAndContext();
const lastValidBlockHeight = blockhashResponse.context.slot + 150;
const rawTransaction = transaction.serialize();
let blockheight = await connection.getBlockHeight();
while (blockheight < lastValidBlockHeight) {
connection.sendRawTransaction(rawTransaction, {
skipPreflight: true,
});
await sleep(500);
blockheight = await connection.getBlockHeight();
}
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