michaelhly / solana-py

Solana Python SDK

Home Page:https://michaelhly.github.io/solana-py

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Transaction simulation failed: Blockhash not found when try to buy a token using USDC

ercole89 opened this issue · comments

Hello,

I've encountered an issue while trying to execute transactions with USDC. The following error is thrown:

solana.rpc.core.RPCException: SendTransactionPreflightFailureMessage { message: "Transaction simulation failed: Blockhash not found", data: RpcSimulateTransactionResult(RpcSimulateTransactionResult { err: Some(BlockhashNotFound), logs: Some([]), accounts: None, units_consumed: Some(0), return_data: None }) }

The token to handle does not have the direct pool to USDC. Just one time the code works, it depends by the blockhash.
This error try to execute a buy operation. I've attached the relevant portion of my code below for your review. Any insights on why this might be happening or how to resolve it would be greatly appreciated.

Code Snippet:

import asyncio
import httpx
import base64
import base58
from solana.rpc.types import TxOpts
from solders.transaction import VersionedTransaction
from solders.keypair import Keypair
from solders import message
from solana.rpc.api import Client

rpc_https = "https://api.mainnet-beta.solana.com/"
usdc_mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
slippage = 10  #10%
private_key='INSERT YOUR PRIVATE KEY'
keypair=Keypair.from_bytes(base58.b58decode(private_key))
public_address = keypair.pubkey()

async def buy(usdc_amount, token_mint_to_buy):
    usdc_decimals = 10 ** 6
    client = Client(rpc_https)

    opts = TxOpts(
        skip_confirmation=False,
        skip_preflight=False,
        max_retries=3
    )
    api_link = f"https://quote-api.jup.ag/v6/quote?inputMint={usdc_mint}&outputMint={token_mint_to_buy}&amount={int(usdc_amount * usdc_decimals)}&slippageBps={slippage}"
    async with httpx.AsyncClient() as clientJupiter:
        response = await clientJupiter.get(api_link)
    quote = response.json()

    parameters = {
        "quoteResponse": quote,
        "userPublicKey": str(public_address),
        "wrapUnwrapSOL": True,
        "computeUnitPriceMicroLamports": 50 * 14000,  #fee
    }

    newResponse = await httpx.AsyncClient().post("https://quote-api.jup.ag/v6/swap", json=parameters)
    swap_transaction = newResponse.json()['swapTransaction']

    raw_txn = VersionedTransaction.from_bytes(base64.b64decode(swap_transaction))
    signature = keypair.sign_message(message.to_bytes_versioned(raw_txn.message))
    signed_txn = VersionedTransaction.populate(raw_txn.message, [signature])

    result = client.send_raw_transaction(bytes(signed_txn), opts)
    txid = result.value
    return txid

async def main():

    ### BUY FUNCTION ###
    token_to_handle = '4icEZCrEYNop2ZaMMCkRHaNzkt6xG9BpijMCQV7mpw6Z' # rocky
    usdc_amount_human_readable = 5  #buy 5 dollars of rocky

    buy_result = await buy(usdc_amount_human_readable, token_to_handle)
    print(f"Buy Result: {buy_result}")

if __name__ == "__main__":
    asyncio.run(main())

bump

I was running into the same issue, and after reading this I tried setting the skip_preflight to True and it worked the first time. Maybe try changing that option and see if it works.

yea, it works 50% of the time doing that. its something to do with VersionedTxns not being able to specify the blockhash directly myself. With legacy txns you can query the node right before you want to sign/send and make sure you're using the latest blockhash directly by adding it to the txn. VersionedTxns did away with this i guess?

Yea I noticed the same thing, there was an error about not being able to specify blockhash with VersionedTransactions, and when I compare the blockhash I'm fetching it doesn't match the one from the message in the VersionedTransaction. I thought of updating the recent transaction value that is in the message but I couldn't figure out how to do that. Perhaps if I deconstruct => reconstruct the entire thing. I'll report back if I figure out how to do it.

Getting the same issue, any work around this yet?

try with:

opts = TxOpts(
        skip_preflight=True,
    preflight_commitment='processed'
)