# Initialize metrics analyzer
metrics = QuantumMetrics()
# Check balance
print("\n💰 Checking SOL Balance...")
balance = trader.get_sol_balance()
print(f"Current Balance: {balance:.4f} SOL")
# Test small trade
amount = 0.01 # 0.01 SOL
print(f"\n🔄 Testing trade: {amount} SOL -> USDC")
# Execute trade
signature = trader.execute_trade("BUY", 23.45) # changed amount to price
print(f"📝 Transaction signature: {signature}")
# Get market data
market_data = {
'price': 23.45,
'volume': 1000.0
}
# Update metrics
metrics.update(market_data, {})
# Check new balance
new_balance = trader.get_sol_balance()
print(f"\n💰 New Balance: {new_balance:.4f} SOL")
print(f"💫 Balance Change: {(new_balance - balance):.4f} SOL")
except Exception as e:
print(f"\n❌ Error: {str(e)}")
raise
finally:
print("\n✨ Test Complete") (quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\tests\test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
🚀 Testing Solana Rust Bot
SOL Balance: 0.361457113
Error during testing: 'builtins.RaydiumTrader' object has no attribute 'get_market_state'
(quantum_beast) PS C:\solana_rust_bot> (quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\tests\test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
🚀 Testing Solana Rust Bot
SOL Balance: 0.361457113
Error during testing: 'builtins.RaydiumTrader' object has no attribute 'get_market_state'
(quantum_beast) PS C:\solana_rust_bot> v(quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\tests\test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
🚀 Testing Solana Rust Bot
SOL Balance: 0.361457113
Error during testing: 'builtins.RaydiumTrader' object has no attribute 'get_market_state'
(quantum_beast) PS C:\solana_rust_bot> (quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\tests\test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
🚀 Testing Solana Rust Bot
SOL Balance: 0.361457113
Error during testing: 'builtins.RaydiumTrader' object has no attribute 'get_market_state'
(quantum_beast) PS C:\solana_rust_bot> (quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\tests\test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
🚀 Testing Solana Rust Bot
SOL Balance: 0.361457113
Error during testing: 'builtins.RaydiumTrader' object has no attribute 'get_market_state'
(quantum_beast) PS C:\solana_rust_bot> (quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\tests\test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
🚀 Testing Solana Rust Bot
SOL Balance: 0.361457113
Error during testing: 'builtins.RaydiumTrader' object has no attribute 'get_market_state'
(quantum_beast) PS C:\solana_rust_bot> (quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\tests\test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
🚀 Testing Solana Rust Bot
SOL Balance: 0.361457113
Error during testing: 'builtins.RaydiumTrader' object has no attribute 'get_market_state'
(quantum_beast) PS C:\solana_rust_bot> (quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\tests\test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
🚀 Testing Solana Rust Bot
SOL Balance: 0.361457113
Error during testing: 'builtins.RaydiumTrader' object has no attribute 'get_market_state'
(quantum_beast) PS C:\solana_rust_bot>
Assistant
The error message you are encountering indicates that the RaydiumTrader object does not have an attribute called get_market_state. This suggests that the method might be missing from the RaydiumTrader class or is named differently than you expect.
To resolve this issue, you can take the following steps:
Check the Implementation: Look into the RaydiumTrader class implementation to verify whether the get_market_state method exists. If it’s supposed to retrieve market state data, check if there is a method that serves the same purpose but has a different name.
List Available Methods: If you have access to the RaydiumTrader class definition, you can list out all available methods using the dir() function:
python
print(dir(trader))
This will help you see all the methods available in the RaydiumTrader class.
Documentation: If the code is part of an external library, consult the documentation for the solana_rust_bot package to understand what methods are available, and if there are alternative approaches to get the market state.
Error Handling: You could add additional error handling to manage cases where the method does not exist. This would prevent your program from crashing and provide a clearer message about what went wrong.
If you find that get_market_state is indeed not part of the RaydiumTrader class, you will need to utilize an alternative method (if one exists) to retrieve market data or implement that functionality yourself.
Here’s how you might adapt your code to help troubleshoot further:
python
try:
print("\n📡 Initializing trader...")
trader = RaydiumTrader("id.json")
# List trader methods (for debugging purposes)
print("Available methods in RaydiumTrader:", dir(trader))
# Proceed with checking balance and trading...
except Exception as e:
print(f"\n❌ Error: {str(e)}")
finally:
print("\n✨ Test Complete")
This should help you determine what methods are available to you in the RaydiumTrader instance. Once you identify the correct method for fetching market data, you can update your test.py script accordingly.
User
make a test script that wil try to use my lib.rs methods? please
Assistant
Certainly! If you want to test methods from your lib.rs in a Rust project, you can create a Rust test script using cargo test. Testing in Rust is usually built into the language, and you typically write tests within your Rust files. However, for demonstration purposes, I’ll show you how to set up an external test script.
Here’s how you can create a basic test script in Rust:
Setup Your Cargo Project: If you haven't already, create a new Cargo project:
bash
cargo new my_solana_project
cd my_solana_project
Add Dependencies: Edit your Cargo.toml to add any necessary dependencies. For the sake of example, let's assume your library does not have external dependencies.
Write Your Library Code: In src/lib.rs, implement some methods that you want to test:
rust
// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
// Other functions you want to test...
Create a Test Module: You can create a test module at the bottom of your lib.rs file to test these functions directly:
rust
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn test_subtract() {
assert_eq!(subtract(5, 3), 2);
}
// Add more tests for other methods...
}
Run Your Tests: You can run your tests using the following command in the terminal:
bash
cargo test
External Test Script
If you specifically want to create a separate script (outside of your main library), you can create a new file, tests/test_script.rs, which would automatically be included by Cargo's testing framework:
rust
User
write a python script that uses pyo3 and imports my lib.rs functions and make the full test script
Assistant
To create a Python script that uses PyO3 to call functions from your Rust library (lib.rs), you need to follow several steps, including building your Rust library as a Python extension. Below is a step-by-step guide along with a Python script to test the functionality.
Step 1: Setup Your Rust Library
Create a New Rust Library:
If you haven't done so, create a new Rust library:
bash
cargo new --lib my_solana_lib
cd my_solana_lib
Add PyO3 Dependency:
Add pyo3 to your Cargo.toml:
toml
[lib]
crate-type = ["cdylib"]
[dependencies]
pyo3 = { version = "0.18", features = ["extension-module"] }
Implement Your Functions:
Here’s an example of what your src/lib.rs might look like:
rust
use pyo3::prelude::*;
#[pyfunction]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[pyfunction]
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
#[pymodule]
fn my_solana_lib(py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(add, m)?)?;
m.add_function(wrap_pyfunction!(subtract, m)?)?;
Ok(())
}
Step 2: Build the Rust Library
Build with Maturin:
Install maturin if you haven't:
bash
pip install maturin
Build the Python Module:
Inside your Rust library directory:
bash
maturin develop
Step 3: Write Your Python Test Script
Now that your Rust library is built as a Python module, you can write a test script that imports and tests these functions. Here’s a complete Python script:
python
User
Traceback (most recent call last):
File "C:\solana_rust_bot\src\python\main.py", line 16, in
from solana_rust_bot import QuantumTrader
ImportError: cannot import name 'QuantumTrader' from 'solana_rust_bot' (C:\Users\Orsen\anaconda3\envs\quantum_beast\lib\site-packages\solana_rust_bot_init_.py)
(quantum_beast) PS C:\solana_rust_bot>
Assistant
The error message you are encountering indicates that Python is unable to import the QuantumTrader class (or function) from the solana_rust_bot module. This can happen due to several reasons. Here are some troubleshooting steps to help you resolve this issue:
1. Verify Module Structure
Ensure that your module structure is correct. Here’s a typical structure for a Python package:
code
solana_rust_bot/
│
├── src/
│ ├── python/
│ │ ├── main.py # Your main Python script
│ ├── lib.rs # Your Rust library code
│ ├── ...
├── __init__.py # Required for Python package
└── setup.py # If you are using setuptools
Make sure that __init__.py is present in the solana_rust_bot directory. This file can be empty or can contain import statements for exposing specific classes or functions.
2. Check __init__.py
In solana_rust_bot/__init__.py, ensure that you have imported the QuantumTrader if you want it to be accessible from the package level. For example, if QuantumTrader is defined in another module, import it like this:
python
from .quantum_trader import QuantumTrader # Assuming QuantumTrader is in quantum_trader.py
3. Check the Class Definition
Ensure that the QuantumTrader class actually exists in the specified module and is implemented correctly. For instance, if QuantumTrader is defined in a file named quantum_trader.py, make sure it looks like this:
python
# src/quantum_trader.py
class QuantumTrader:
def __init__(self):
# Initialization code
pass
# Other methods...
4. Check for Typos
Make sure there are no typos in your import statements. Check both the imported name and the module name.
5. Rebuild Your Module
If you recently made changes to your Rust code or how you are exposing it to Python, you'll need to rebuild the Python module. Use maturin or setuptools as needed.
User
Path: C:\solana_rust_bot\src\id.json
Public Key: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
Status: ACTIVE
An unexpected error occurred: 'builtins.RaydiumTrader' object has no attribute 'get_sol_balance'
Traceback (most recent call last):
File "C:\solana_rust_bot\src\python\quick_test.py", line 30, in main
sol_balance = trader.get_sol_balance()
AttributeError: 'builtins.RaydiumTrader' object has no attribute 'get_sol_balance'
(quantum_beast) PS C:\solana_rust_bot> use {
pyo3::{prelude::*, exceptions::PyValueError},
serde_json::json,
solana_client::rpc_client::RpcClient,
solana_sdk::{
commitment_config::CommitmentConfig,
pubkey::Pubkey,
signature::Keypair,
signer::Signer,
transaction::Transaction,
compute_budget::ComputeBudgetInstruction,
instruction::{AccountMeta, Instruction},
program_pack::Pack,
},
std::{sync::Arc, time::Duration, fs::File, io::Read, path::PathBuf, str::FromStr},
base64::{Engine as _, engine::general_purpose::STANDARD},
reqwest::blocking::Client,
spl_token,
};
impl TradeConfig {
fn new(keypair_path: &str) -> PyResult {
let mut file = File::open(keypair_path)
.map_err(|e| PyValueError::new_err(format!("Failed to open keypair file: {}", e)))?;
code
let mut contents = String::new();
file.read_to_string(&mut contents)
.map_err(|e| PyValueError::new_err(format!("Failed to read keypair file: {}", e)))?;
let keypair_bytes: Vec<u8> = serde_json::from_str(&contents)
.map_err(|e| PyValueError::new_err(format!("Failed to parse keypair JSON: {}", e)))?;
let keypair = Keypair::from_bytes(&keypair_bytes)
.map_err(|e| PyValueError::new_err(format!("Failed to create keypair: {}", e)))?;
let public_key = keypair.pubkey().to_string();
Ok(Self {
keypair_path: PathBuf::from(keypair_path),
keypair: Arc::new(keypair),
public_key,
slippage_bps: 50,
priority_fee: 15000,
})
}
Assistant
From the provided information, your RaydiumTrader class in Rust does not have a method called get_sol_balance, which is causing your Python test script to fail. Instead, you should implement a method in your RaydiumTrader class to fetch the SOL balance.
Below are the steps to address this issue, including the implementation of the get_sol_balance method in your Rust code and how to update your Python test script accordingly.
Step 1: Update the RaydiumTrader Class
You need to add the get_sol_balance method to your RaydiumTrader class. This method should fetch the SOL balance of the trader's wallet using the rpc_client.
Here is how you can implement this:
rust
#[pymethods]
impl RaydiumTrader {
// ... existing methods ...
fn get_sol_balance(&self) -> PyResult<f64> {
// Get the public key of the trader
let public_key = self.config.keypair.pubkey();
// Fetch the account info using the RPC client
let account_info = self.rpc_client
.get_account(&public_key)
.map_err(|e| PyValueError::new_err(format!("Failed to get account info: {}", e)))?;
// Extract the SOL balance (keep in mind that this is in lamports)
Ok(account_info.lamports as f64 / 1_000_000_000.0) // Convert lamports to SOL
}
}
Make sure to also verify that the Account structure from Solana client has the required fields. Following the addition of this method, rebuild your Rust library with maturin develop as previously instructed.
Step 2: Update Your Python Test Script
Here's the updated Python script that tests the functionalities of the RaydiumTrader class along with the addition of get_sol_balance, and also creates the required token account:
python
User
(quantum_beast) PS C:\solana_rust_bot> solana balance
[2024-11-26T11:33:09.791956700Z DEBUG reqwest::connect] starting new connection: https://marga-e56m84-fast-mainnet.helius-rpc.com/
[2024-11-26T11:33:09.792230600Z DEBUG hyper::client::connect::dns] resolving host="marga-e56m84-fast-mainnet.helius-rpc.com"
[2024-11-26T11:33:09.820387500Z DEBUG hyper::client::connect::http] connecting to [2606:4700:4400::ac40:9757]:443
[2024-11-26T11:33:09.835459800Z DEBUG hyper::client::connect::http] connected to [2606:4700:4400::ac40:9757]:443
[2024-11-26T11:33:09.871233500Z DEBUG hyper::proto::h1::io] flushed 257 bytes
[2024-11-26T11:33:10.059475600Z DEBUG hyper::proto::h1::io] parsed 14 headers
[2024-11-26T11:33:10.059700900Z DEBUG hyper::proto::h1::conn] incoming body is chunked encoding
[2024-11-26T11:33:10.060542400Z DEBUG hyper::proto::h1::decode] incoming chunked header: 0x63 (99 bytes)
[2024-11-26T11:33:10.060764900Z DEBUG reqwest::connect] starting new connection: https://marga-e56m84-fast-mainnet.helius-rpc.com/
[2024-11-26T11:33:10.060928400Z DEBUG hyper::client::connect::dns] resolving host="marga-e56m84-fast-mainnet.helius-rpc.com"
[2024-11-26T11:33:10.061300500Z DEBUG hyper::client::connect::http] connecting to [2606:4700:4400::ac40:9757]:443
[2024-11-26T11:33:10.081969000Z DEBUG hyper::client::connect::http] connected to [2606:4700:4400::ac40:9757]:443
[2024-11-26T11:33:10.114763300Z DEBUG hyper::proto::h1::io] flushed 329 bytes
[2024-11-26T11:33:10.613236500Z DEBUG hyper::proto::h1::io] parsed 14 headers
[2024-11-26T11:33:10.613463500Z DEBUG hyper::proto::h1::conn] incoming body is chunked encoding
[2024-11-26T11:33:10.613670000Z DEBUG hyper::proto::h1::decode] incoming chunked header: 0x73 (115 bytes)
0.361457113 SOL
(quantum_beast) PS C:\solana_rust_bot> i can just type solana balance for my balance
Assistant
It appears that you're able to successfully check your SOL balance using the command-line tool by running solana balance, which indicates that your Solana CLI setup is functioning properly and you have access to your wallet.
To integrate this functionality into your Rust and Python implementation, you should ensure that the mechanism for getting the SOL balance matches what the CLI is doing. Here's how you can refine your Rust and Python code based on your successful CLI usage.
Step 1: Use the Same RPC Endpoint
Make sure that your RaydiumTrader class is configured to use the same RPC endpoint that the Solana CLI uses. Since you are using the Helios RPC endpoint (https://marga-e56m84-fast-mainnet.helius-rpc.com), ensure that this is correctly set in your RaydiumTrader class.
Your current code already defines the RPC client properly, so make sure that any calls you make also utilize this properly configured RPC.
Step 2: Ensure SOL Balance Retrieval Matches CLI
To get the SOL balance correctly, the logic in get_sol_balance should match what the CLI is doing. It should include fetching the account's lamport balance and converting it to SOL, as illustrated previously.
Here’s the final check for your Rust 'get_sol_balance' method:
rust
fn get_sol_balance(&self) -> PyResult<f64> {
// Get the public key of the trader
let public_key = self.config.keypair.pubkey();
// Fetch the account info using the RPC client
let account_info = self.rpc_client
.get_account(&public_key)
.map_err(|e| PyValueError::new_err(format!("Failed to get account info: {}", e)))?;
// Extract the SOL balance (the balance is in lamports)
Ok(account_info.lamports as f64 / 1_000_000_000.0) // Convert lamports to SOL
}
Step 3: Test Your Python Functionality
With the Rust method implemented correctly, you can use the Python script to check the SOL balance. You've already set this up in the previously provided quick_test.py script. Just make sure it calls the method to retrieve the SOL balance properly.
Here’s the key part of your Python script that checks the balance:
python
User
doesnt jupiter v6 do all that anyway
Assistant
Yes, Jupiter Aggregator's API provides functionality that simplifies trading and liquidity aggregation across multiple Solana markets, which can help you retrieve prices, execute trades, and more without needing to manually manage all the details yourself. This means that if you're using the Jupiter API, a lot of the backend functions such as balance inquiries, trade executions, and price calculations can indeed be handled easily through their service.
Overview of Jupiter API Capabilities
Here are some functionalities that Jupiter's API provides, which may alleviate some of the tasks you'd otherwise need to implement manually:
Price Quotes: Retrieve the best prices for swaps between various tokens without needing to fetch market data manually.
Trade Execution: Execute trades programmatically by preparing and sending transactions to the Solana blockchain, which can significantly streamline the process.
Market Data: Get the latest market data, including pricing and liquidity information, for supported pairs.
Liquidity Detection: Automatically find the best liquidity pools for trades, helping users to avoid slippage and bad price execution.
Error Handling: Simplified error messages and feedback that correlate with the actions you are taking.
Given these capabilities, if your goal is primarily to trade tokens on Solana (like SOL and BONK), and you are using the Jupiter API, you can leverage it to perform tasks like fetching balances and executing trades directly without having to implement the underlying logic for each operation yourself.
Example Jupiter API Integration
Here’s how you might streamline your existing Rust/Python implementation if you're using Jupiter for price swaps and trade execution. Below is a high-level overview of how you'd interact with the Jupiter API:
1. Get Price Quote
You can retrieve the swap price between two tokens using the Jupiter API. This reduces the need to manage price calculations manually.
rust
fn get_price_quote(&self, input_mint: &str, output_mint: &str, amount: f64) -> PyResult<JsonValue> {
let url = format!("https://quote-api.jup.ag/v6/quote?market={}&inputMint={}&outputMint={}&amount={}", "SOL_USDC", input_mint, output_mint, amount);
let response = self.client.get(&url)
.send()
.map_err(|e| PyValueError::new_err(format!("Failed to get price quote: {}", e)))?;
let json: JsonValue = response.json().map_err(|e| PyValueError::new_err(format!("Failed to parse JSON response: {}", e)))?;
Ok(json)
}
User
yeah im not touching my lib.rs file so dont evne think about it
Assistant
Understood! If you're focusing on using the existing functionality from your lib.rs file without modifying it, we can focus solely on using the Jupiter API and enhancing your Python script accordingly.
Using Jupiter API in Python
Since you intend to integrate Jupiter API functionalities into your Python script, let’s create a more streamlined flow for fetching trading quotes and executing trades using the Jupiter API without requiring any changes to your Rust library.
Here's a full example of how your Python quick_test.py script can leverage the Jupiter API, assuming you're using the previously defined functions from your Rust library only for balance checks and keypair verification, while using Jupiter for price and trade execution.
Updated Python Script
Below is an updated version of your Python script that utilizes the Jupiter API for trade execution while keeping the balance inquiry via your existing Rust implementation.
Make sure you have the requests library installed in your Python environment to interact with the Jupiter API:
bash
pip install requests
Now, here’s the modified quick_test.py:
python
User
om requests) (2.2.3)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\orsen\anaconda3\envs\quantum_beast\lib\site-packages (from requests) (2024.8.30)
(quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\src\python\quick_test.py"
Loaded keypair: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
Keypair Status:
Path: C:\solana_rust_bot\src\id.json
Public Key: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
Status: ACTIVE
An unexpected error occurred: 'builtins.RaydiumTrader' object has no attribute 'get_sol_balance'
Traceback (most recent call last):
File "C:\solana_rust_bot\src\python\quick_test.py", line 51, in main
sol_balance = trader.get_sol_balance()
AttributeError: 'builtins.RaydiumTrader' object has no attribute 'get_sol_balance'
(quantum_beast) PS C:\solana_rust_bot>
Assistant
The error message you are seeing indicates that the RaydiumTrader object does not have a method called get_sol_balance. This could happen for a couple of reasons:
Missing Method: The get_sol_balance method may not have been defined in your RaydiumTrader class in lib.rs. Please double-check to ensure that you have implemented this method correctly in your Rust code.
Rebuild Issues: If you've recently added the get_sol_balance method to your Rust code, make sure you rebuild your Python extension module with the latest changes using maturin develop.
Step-by-Step Troubleshooting
Step 1: Confirm the Method Exists
Make sure the following method is defined within the RaydiumTrader class in your lib.rs file:
rust
#[pymethods]
impl RaydiumTrader {
// Other methods...
fn get_sol_balance(&self) -> PyResult<f64> {
let public_key = self.config.keypair.pubkey();
let account_info = self.rpc_client
.get_account(&public_key)
.map_err(|e| PyValueError::new_err(format!("Failed to get account info: {}", e)))?;
Ok(account_info.lamports as f64 / 1_000_000_000.0) // Convert lamports to SOL
}
}
Step 2: Build the Program
After confirming that the get_sol_balance method is defined correctly, you need to rebuild the Rust module so that changes can be reflected in Python.
Run the following command inside your Rust project directory:
bash
maturin develop
This command should rebuild your Rust project and ensure that the new functionalities are available in your Python environment.
Step 3: Verify the Python Interface
To ensure that your RaydiumTrader is exposing the expected methods, you can add a simple test in your Python script to list all methods:
// tests/test_script.rs
use my_solana_project::add; // Assuming your library is named `my_solana_project`
use my_solana_project::subtract;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(1, 2), 3);
assert_eq!(add(-1, -1), -2);
assert_eq!(add(-1, 1), 0);
}
#[test]
fn test_subtract() {
assert_eq!(subtract(5, 3), 2);
assert_eq!(subtract(3, 5), -2);
assert_eq!(subtract(0, 0), 0);
}
}
Notes:
The tests are located in the tests/ directory, which is a convention in Rust projects for integration tests.
Tests will automatically be compiled and run by cargo test.
Each test function is marked with the #[test] attribute to indicate that it's a test case.
You can include more methods from your lib.rs file in your tests by importing them as shown.
Summary:
Create your Rust library with methods to be tested.
Write tests in the same file or in a separate tests directory.
Run the tests using cargo test.
This setup provides a robust way to verify the functionality of your lib.rs methods directly in Rust. If your methods interact with Solana or perform specific trading actions, ensure to mock or simulate those actions as needed to isolate your tests.
# test_my_solana_lib.py
import my_solana_lib # Ensure that your module name matches here
def test_add():
assert my_solana_lib.add(1, 2) == 3
assert my_solana_lib.add(-1, 1) == 0
assert my_solana_lib.add(-5, -5) == -10
def test_subtract():
assert my_solana_lib.subtract(5, 3) == 2
assert my_solana_lib.subtract(3, 5) == -2
assert my_solana_lib.subtract(0, 0) == 0
if __name__ == "__main__":
print("Running tests...")
# Run tests
test_add()
test_subtract()
print("All tests passed!")
Step 4: Run Your Test Script
With everything set up, you can run your Python test script:
bash
python test_my_solana_lib.py
Summary
Rust Implementation: Implement your library functions using PyO3 and expose them to Python.
Build the Library: Use maturin to build and install the library so it can be imported into Python.
Testing in Python: Write a Python script to test the functionality of the library you just created and run the tests.
By following these steps, you'll have a complete testing setup for your Rust functions through Python using PyO3. If you have more functions in lib.rs, simply add them in the same way as shown, and create corresponding test cases in your Python script.
For example, if you are using maturin:
bash
maturin develop
6. Test Import in Python Shell
To further diagnose the issue, open a Python shell (make sure you're in the correct virtual environment) and try to manually import the module:
python
import solana_rust_bot
print(dir(solana_rust_bot)) # Check what is available in the module
7. Ensure Environment Consistency
Ensure that the Python environment (Anaconda environment quantum_beast) where you are trying to run the script has access to the installed package. If you installed the package in a different environment, you might have issues with imports.
8. Check for Circular Imports
If QuantumTrader is dependent on another module that also tries to import solana_rust_bot, you might get an import error due to circular imports.
Example of an __init__.py File
Here’s an expanded example of what your __init__.py might look like to properly export the QuantumTrader:
python
# solana_rust_bot/__init__.py
from .quantum_trader import QuantumTrader
# Import other modules or classes if necessary
Summary
By following these steps, you should be able to identify the issue causing the import error. Make sure to verify the structure of your Python package, check the correct class definition, and confirm that your installation is up to date. If all else fails, examining the directory structure and debugging your import paths will often lead you to the solution.
#[pymodule]
fn solana_rust_bot(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::()?;
Ok(()) fix the test script here polkease from solana_rust_bot import RaydiumTrader
import os
import traceback
import time
if not os.path.exists(keypair_path):
print(f"Keypair file not found at: {keypair_path}")
return
trader = RaydiumTrader(keypair_path)
print(trader.verify_keypair())
sol_balance = trader.get_sol_balance()
print(f"SOL Balance: {sol_balance} SOL")
trade_amount = 0.1 # 0.1 SOL worth of BONK
if sol_balance < trade_amount + 0.01:
print(f"Insufficient SOL. Need at least {trade_amount + 0.01} SOL")
return
# Explicitly create BONK token account
bonk_account = create_token_account(trader, BONK_MINT)
# Execute BONK buy
try:
print(f"Attempting to buy BONK with {trade_amount} SOL...")
trade_signature = trader.execute_trade("BUY", trade_amount)
print(f"BONK Buy executed. Transaction Signature: {trade_signature}")
# Wait and check BONK balance
time.sleep(15) # Wait for transaction to confirm
bonk_balance = trader.get_token_balance(BONK_MINT)
print(f"BONK Balance: {bonk_balance} BONK")
except Exception as trade_e:
print(f"BONK trade execution failed: {trade_e}")
traceback.print_exc()
except Exception as e:
print(f"An unexpected error occurred: {e}")
traceback.print_exc()
if name == "main":
main()
}
# quick_test.py
from solana_rust_bot import RaydiumTrader
import os
import traceback
import time
# BONK token mint address
BONK_MINT = "DezXAZ8z7PnrnRkjXz3LdC4Yo7EVh5ZRDyM5WSyLjwiv"
def create_token_account(trader, mint):
try:
# This method will create the Associated Token Account if it doesn't exist
token_account = trader.get_token_account(mint)
print(f"Token Account for {mint}: {token_account}")
return token_account
except Exception as e:
print(f"Error creating token account: {e}")
raise
def main():
try:
keypair_path = r"C:\solana_rust_bot\src\id.json"
if not os.path.exists(keypair_path):
print(f"Keypair file not found at: {keypair_path}")
return
trader = RaydiumTrader(keypair_path)
print(trader.verify_keypair())
# Now using the added get_sol_balance method
sol_balance = trader.get_sol_balance()
print(f"SOL Balance: {sol_balance} SOL")
trade_amount = 0.1 # 0.1 SOL worth of BONK
if sol_balance < trade_amount + 0.01:
print(f"Insufficient SOL. Need at least {trade_amount + 0.01} SOL")
return
# Explicitly create BONK token account
bonk_account = create_token_account(trader, BONK_MINT)
# Execute BONK buy
try:
print(f"Attempting to buy BONK with {trade_amount} SOL...")
trade_signature = trader.execute_trade("BUY", trade_amount)
print(f"BONK Buy executed. Transaction Signature: {trade_signature}")
# Wait and check BONK balance
time.sleep(15) # Wait for transaction to confirm
bonk_balance = trader.get_token_balance(BONK_MINT)
print(f"BONK Balance: {bonk_balance} BONK")
except Exception as trade_e:
print(f"BONK trade execution failed: {trade_e}")
traceback.print_exc()
except Exception as e:
print(f"An unexpected error occurred: {e}")
traceback.print_exc()
if __name__ == "__main__":
main()
Summary of Changes
Implement get_sol_balance in Rust: Added a method to fetch the SOL balance from the trader's wallet.
Update Python Test Script: Adjusted the test script to call the new method get_sol_balance().
Step 3: Rebuild and Test
After making the changes in your Rust code, rebuild the library inside the project:
bash
maturin develop
Run your updated Python script:
bash
python quick_test.py
This setup should now allow for fetching the SOL balance properly, and subsequent calls to execute trades should function as intended. If you encounter any more errors, make sure to carefully check the implementation and error messages for additional context.
try:
keypair_path = r"C:\solana_rust_bot\src\id.json"
if not os.path.exists(keypair_path):
print(f"Keypair file not found at: {keypair_path}")
return
trader = RaydiumTrader(keypair_path)
print(trader.verify_keypair())
# Now using the added get_sol_balance method
sol_balance = trader.get_sol_balance()
print(f"SOL Balance: {sol_balance} SOL")
except Exception as e:
print(f"An unexpected error occurred: {e}")
traceback.print_exc()
Step 4: Keep Your Environment Updated
Keep in mind that you must ensure that the Solana Rust library is correctly built and the Python bindings are refreshed after any changes to the Rust code. When making changes to your Rust code or its dependencies, run:
bash
maturin develop
Step 5: Running the Tests Again
Now you can run your script again to check the balance, execute trades, and perform other actions as intended. The output should match what you see from the Solana CLI to ensure consistency.
Closing Thoughts
Testing with the solana balance command has validated that your setup works correctly and allows for cross-checking any discrepancies between your Rust and Python implementations. Continue to refine your methods based on the requirements of your project and the behavior of the Solana blockchain. If you have further issues, feel free to share details for additional help!
2. Execute Trade
Instead of manually forming transactions, you could interact with a method provided by Jupiter to handle the execution:
rust
fn execute_trade(&self, input_mint: &str, output_mint: &str, amount: f64) -> PyResult<String> {
// First get the price quote
let quote = self.get_price_quote(input_mint, output_mint, amount)?;
// Now structure the transaction based on Jupiter's expected format and execute
// This part would depend on the detailed API docs provided by Jupiter.
}
Simplifying Your Current Implementation
Here’s a summarized strategy to integrate Jupiter's system instead of manually managing trades:
Use the Jupiter API to Get Quotes: Whenever you want to perform a trade, use the Jupiter endpoint to get a quote for the amount of tokens you're interested in.
Use the Jupiter API for Executing Trades: Allow Jupiter to handle the transaction initiation and posting to the Solana network.
Fetch Balances from Jupiter: If needed, handle balance queries using either the Jupiter API or solana balance from the CLI depending on your specific requirements.
Conclusion
By leveraging the Jupiter API's capabilities, you can simplify your implementation, reduce boilerplate code, and gain access to potentially better pricing and liquidity without managing everything yourself. If you are building a trading bot or an automated trading system, using the API for price quotes and transaction handling can greatly enhance efficiency and reliability.
Make sure to consult the Jupiter API documentation for specific endpoints, request formats, and detailed examples to streamline both price retrieving and trading actions.
import os
import requests
import traceback
import time
from solana_rust_bot import RaydiumTrader
# BONK token mint address
BONK_MINT = "DezXAZ8z7PnrnRkjXz3LdC4Yo7EVh5ZRDyM5WSyLjwiv"
SOL_MINT = "So11111111111111111111111111111111111111112"
def get_price_quote(input_mint, output_mint, amount):
try:
url = f"https://quote-api.jup.ag/v6/quote?inputMint={input_mint}&outputMint={output_mint}&amount={amount}"
response = requests.get(url)
response.raise_for_status() # Raise an error for bad responses
return response.json()
except requests.RequestException as e:
print(f"Error fetching price quote: {e}")
raise
def execute_trade(trader, input_mint, output_mint, amount):
try:
quote = get_price_quote(input_mint, output_mint, amount)
print(f"Price Quote: {quote}")
# Ensure there's a valid route to trade
if 'data' not in quote or not quote['data']:
print("No valid route found for the trade.")
return
# Assuming you want to execute the first route available
route = quote['data'][0]
signature = trader.execute_trade("BUY", route['amountIn']) # Adjust to pass amount correctly
return signature
except Exception as e:
print(f"Failed to execute trade: {e}")
traceback.print_exc()
def main():
try:
keypair_path = r"C:\solana_rust_bot\src\id.json"
if not os.path.exists(keypair_path):
print(f"Keypair file not found at: {keypair_path}")
return
trader = RaydiumTrader(keypair_path)
print(trader.verify_keypair())
# Retrieve SOL balance using the existing rust function
sol_balance = trader.get_sol_balance()
print(f"SOL Balance: {sol_balance:.4f} SOL")
trade_amount = 0.1 # Amount of SOL to trade for BONK
if sol_balance < trade_amount + 0.01:
print(f"Insufficient SOL. Need at least {trade_amount + 0.01:.4f} SOL")
return
# Execute BONK buy using Jupiter API quote
try:
print(f"Attempting to buy BONK with {trade_amount:.4f} SOL...")
trade_signature = execute_trade(trader, SOL_MINT, BONK_MINT, trade_amount)
print(f"BONK Buy executed. Transaction Signature: {trade_signature}")
# Wait and check BONK balance
time.sleep(15) # Wait for transaction to confirm
bonk_balance = trader.get_token_balance(BONK_MINT)
print(f"BONK Balance: {bonk_balance:.4f} BONK")
except Exception as trade_e:
print(f"BONK trade execution failed: {trade_e}")
traceback.print_exc()
except Exception as e:
print(f"An unexpected error occurred: {e}")
traceback.print_exc()
if __name__ == "__main__":
main()
What This Script Does:
Price Quote Retrieval: Uses the Jupiter API to fetch the price quote for swapping SOL to BONK.
Trade Execution: Executes a trade based on the retrieved quote, leveraging the existing ability in your Rust library.
Uses Existing Rust Functions: Fetches and verifies the trader's keypair and SOL balance without modifying your Rust implementation.
Notes:
Error Handling: The script includes basic error handling to ensure any issues with network requests do not crash the program unexpectedly.
Trade Logic: The method for executing a trade (execute_trade) makes a request to the Jupiter API and handles the execution based on the route it provides.
Duration for Confirmation: A sleep duration is included to allow the transaction time to confirm before checking the BONK balance.
Conclusion
With this approach, you can utilize the Jupiter API to streamline your trading operations while still using your existing Rust library for account and balance management. This modular design can help keep your project organized and future-proof. If you have any further requests or need more tweaks to your script, feel free to ask!
# Add this to the top of your main script
print(dir(trader)) # This will print the available methods in the trader instance
# Existing code in main(...)
This line will provide a list of all methods available to the trader object, helping you confirm whether get_sol_balance is present.
Step 4: Python Script Execution
After you’ve confirmed the method is implemented and the module is rebuilt, run your Python script again:
By ensuring that the method get_sol_balance is defined correctly, rebuilding the module, and verifying the available methods, you should be able to resolve the import error. If you continue to experience issues, please share any additional information or code snippets so we can further assist you!