Bestright way to confirm a Solana transaction in Python? - Stack Overflow

admin2025-05-02  0

I'm working on a trading bot for solana using Python. I'm trying to confirm if the transaction has gone through before trying to repeat the whole process again. I have a feeling I'm getting the last valid block height incorrectly as it seems to go above 90 seconds which seems like a long time for the block height not to go over the last valid block height.

# Step 4: Decode and sign the transaction
            app.logger.info("Decoding and signing the transaction...")
            raw_transaction = VersionedTransaction.from_bytes(base64.b64decode(swap_transaction))
            signature = private_key.sign_message(to_bytes_versioned(raw_transaction.message))  # Sign the serialized message
            signed_txn = VersionedTransaction.populate(raw_transaction.message, [signature])  # Populate the transaction
            app.logger.info("Transaction signed successfully.")

            # Getting last valid block height
            latest_blockhash_response = client.get_latest_blockhash("processed")
            last_valid_block_height = json.loads(latest_blockhash_response.to_json())['result']["context"]["slot"]
            app.logger.info(f"Last valid block height: {last_valid_block_height}")

            # Step 5: Send the signed transaction
            app.logger.info("Sending signed transaction to Solana network")
            opts = TxOpts(skip_preflight=False, preflight_commitment=Processed)
            result = client.send_raw_transaction(txn=bytes(signed_txn), opts=opts)
            app.logger.info(f"Transaction sent successfully. Response: {result.to_json()}")

            # Step 6: Extract the transaction ID
            transaction_id = json.loads(result.to_json())['result']
            app.logger.info(f"Transaction ID: {transaction_id}")

            # Step 7: Confirm transaction status
            app.logger.info("Checking transaction confirmation status...")                
            confirmation = client.confirm_transaction(signature, "processed", 0.5, last_valid_block_height)
            confirmation_dict = json.loads(confirmation.to_json())
            app.logger.info(f"Confirmation dict: {confirmation_dict}")
            if "err" in confirmation_dict["result"]["value"][0]:
                error_details = confirmation_dict["result"]["value"][0]["err"]
                if error_details is not None:
                    app.logger.warning(f"Transaction confirmation failed with error: {error_details}")
                    raise RuntimeError(f"Transaction confirmation failed. Error details: {error_details}")
            
            app.logger.info(f"Transaction confirmed: /{transaction_id}")
转载请注明原文地址:http://anycun.com/QandA/1746137319a92089.html