i need my solana_cli.py to instead of what its doing right now i need it to use this command
spl-token unwrap 5TwPK71xyhpkxNQ3WzxvSrpVpj16eDETwmMQJX74BGRX --fee-payer "C:\solana_rust_bot\id.json" --url https://marga-e56m84-fast-mainnet.helius-rpc.com
spl-token wrap 0.7 --fee-payer "C:\solana_rust_bot\id.json" --url https://marga-e56m84-fast-mainnet.helius-rpc.com both of these properly when my solana balance reaches 0.05 solana left inside the main wallet it needs to pause trading for 1minute 20 seconds and it needs to unwrap with the command and then needs to wait 15 seconds to validate retry if failed after running again validates then wraps the solana with the other account for 0.7 solana and then 15 seconds to validate if not again then trys again validates then resumes trading again ? import asyncio
import logging
import time
import torch
import os
from enum import Enum
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
from typing import Optional, Tuple, Dict
from dataclasses import dataclass
Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('solana_cli.log')
]
)
logger = logging.getLogger(name)
class WSOLState(Enum):
IDLE = "idle"
UNWRAPPING = "unwrapping"
WRAPPING = "wrapping"
VERIFYING = "verifying"
ERROR = "error"
@dataclass
class TokenBalances:
sol: float = 0.0
wsol: float = 0.0
timestamp: float = 0.0
class SolanaCLI:
def init(self, trading_core):
"""Initialize SolanaCLI with proper configuration"""
self.trading_core = trading_core
self.state = WSOLState.IDLE
self.last_operation_time = time.time()
# Load environment variables
self.WSOL_TOKEN_ACCOUNT = os.getenv('WSOL_TOKEN_ACCOUNT', '5TwPK71xyhpkxNQ3WzxvSrpVpj16eDETwmMQJX74BGRX')
self.WSOL_MINT = "So11111111111111111111111111111111111111112"
# Configuration
self.MIN_SOL_BALANCE = 0.06
self.WRAP_AMOUNT = 0.7
self.MAX_RETRIES = 3
self.RETRY_DELAY = 2.0
self.BALANCE_CACHE_TIME = 30.0
# File paths
self.BASE_DIR = Path("C:/solana_rust_bot")
self.KEY_FILE = self.BASE_DIR / "id.json"
# Operation state
self.trading_active = True
self.last_balances: Optional[TokenBalances] = None
self.operation_lock = asyncio.Lock()
# Performance optimization
self.thread_pool = ThreadPoolExecutor(max_workers=2)
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if torch.cuda.is_available():
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.benchmark = True
self._verify_environment()
logger.info(f"SolanaCLI initialized with WSOL account: {self.WSOL_TOKEN_ACCOUNT}")
def _verify_environment(self):
"""Verify environment and key files"""
if not self.KEY_FILE.exists():
raise FileNotFoundError(f"Keypair file not found at {self.KEY_FILE}")
if not self.WSOL_TOKEN_ACCOUNT:
raise ValueError("WSOL_TOKEN_ACCOUNT not set")
async def execute_command(self, cmd: str) -> Tuple[int, bytes, bytes]:
"""Execute Solana CLI command"""
try:
process = await asyncio.subprocess.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
return process.returncode, stdout, stderr
except Exception as e:
logger.error(f"Command execution error: {e}")
return -1, b"", str(e).encode()
async def get_token_balance(self, token_account: str) -> float:
"""Get token account balance"""
cmd = f'spl-token balance {token_account} --url https://marga-e56m84-fast-mainnet.helius-rpc.com'
returncode, stdout, stderr = await self.execute_command(cmd)
if returncode == 0:
try:
return float(stdout.decode().strip())
except ValueError:
logger.error("Failed to parse token balance")
return 0.0
return 0.0
async def get_balances(self, force_refresh: bool = False) -> TokenBalances:
"""Get SOL and WSOL balances with caching"""
current_time = time.time()
if (not force_refresh and
self.last_balances and
current_time - self.last_balances.timestamp < self.BALANCE_CACHE_TIME):
return self.last_balances
try:
sol_balance = self.trading_core.get_balance()
wsol_balance = await self.get_token_balance(self.WSOL_TOKEN_ACCOUNT)
self.last_balances = TokenBalances(
sol=sol_balance,
wsol=wsol_balance,
timestamp=current_time
)
return self.last_balances
except Exception as e:
logger.error(f"Balance check error: {e}")
if self.last_balances:
return self.last_balances
return TokenBalances()
async def wrap_sol(self, amount: Optional[float] = None) -> bool:
"""Wrap SOL to WSOL"""
async with self.operation_lock:
if self.state != WSOLState.IDLE:
logger.warning(f"Cannot wrap, current state: {self.state}")
return False
amount = amount or self.WRAP_AMOUNT
self.trading_active = False
self.state = WSOLState.WRAPPING
try:
# Verify sufficient balance
balances = await self.get_balances(force_refresh=True)
if balances.sol < amount + self.MIN_SOL_BALANCE:
logger.error(f"Insufficient SOL balance for wrap: {balances.sol}")
return False
# Execute wrap
cmd = f'spl-token wrap {amount} --fee-payer "C:\solana_rust_bot\id.json" --url https://marga-e56m84-fast-mainnet.helius-rpc.com'
for attempt in range(self.MAX_RETRIES):
returncode, stdout, stderr = await self.execute_command(cmd)
if returncode == 0:
await asyncio.sleep(2)
if await self._verify_wrap_success(amount):
logger.info(f"Wrap successful for {amount} SOL")
return True
logger.error(f"Wrap attempt {attempt + 1} failed: {stderr.decode()}")
if attempt < self.MAX_RETRIES - 1:
await asyncio.sleep(self.RETRY_DELAY * (attempt + 1))
return False
except Exception as e:
logger.error(f"Wrap operation failed: {e}")
return False
finally:
self.trading_active = True
self.state = WSOLState.IDLE
async def unwrap_sol(self) -> bool:
"""Unwrap WSOL to SOL"""
async with self.operation_lock:
if self.state != WSOLState.IDLE:
logger.warning(f"Cannot unwrap, current state: {self.state}")
return False
self.trading_active = False
self.state = WSOLState.UNWRAPPING
try:
# Check WSOL balance
wsol_balance = await self.get_token_balance(self.WSOL_TOKEN_ACCOUNT)
if wsol_balance <= 0:
logger.warning("No WSOL balance to unwrap")
return False
# Execute unwrap
cmd = f'spl-token unwrap {self.WSOL_TOKEN_ACCOUNT} --fee-payer "C:\solana_rust_bot\id.json" --url https://marga-e56m84-fast-mainnet.helius-rpc.com'
for attempt in range(self.MAX_RETRIES):
returncode, stdout, stderr = await self.execute_command(cmd)
if returncode == 0:
await asyncio.sleep(2)
if await self._verify_unwrap_success():
logger.info("Unwrap successful")
return True
logger.error(f"Unwrap attempt {attempt + 1} failed: {stderr.decode()}")
if attempt < self.MAX_RETRIES - 1:
await asyncio.sleep(self.RETRY_DELAY * (attempt + 1))
return False
except Exception as e:
logger.error(f"Unwrap operation failed: {e}")
return False
finally:
self.trading_active = True
self.state = WSOLState.IDLE
async def _verify_wrap_success(self, amount: float) -> bool:
"""Verify wrap operation success"""
try:
new_balances = await self.get_balances(force_refresh=True)
old_balances = self.last_balances or TokenBalances()
wsol_increased = new_balances.wsol > old_balances.wsol
sol_decreased = old_balances.sol - new_balances.sol >= amount
return wsol_increased and sol_decreased
except Exception as e:
logger.error(f"Wrap verification error: {e}")
return False
async def _verify_unwrap_success(self) -> bool:
"""Verify unwrap operation success"""
try:
new_balances = await self.get_balances(force_refresh=True)
old_balances = self.last_balances or TokenBalances()
wsol_decreased = new_balances.wsol < old_balances.wsol
sol_increased = new_balances.sol > old_balances.sol
return wsol_decreased and sol_increased
except Exception as e:
logger.error(f"Unwrap verification error: {e}")
return False
async def monitor_balances(self):
"""Monitor SOL and WSOL balances"""
logger.info("Starting balance monitoring...")
while True:
try:
balances = await self.get_balances(force_refresh=True)
logger.info(f"Current balances - SOL: {balances.sol:.6f}, WSOL: {balances.wsol:.6f}")
if balances.sol <= self.MIN_SOL_BALANCE and balances.wsol > 0:
logger.info(f"SOL balance ({balances.sol}) below threshold. Unwrapping WSOL...")
await self.unwrap_sol()
await asyncio.sleep(2)
elif balances.sol >= self.WRAP_AMOUNT:
logger.info(f"SOL balance ({balances.sol}) above threshold. Wrapping SOL...")
await self.wrap_sol()
await asyncio.sleep(30)
except Exception as e:
logger.error(f"Balance monitoring error: {e}")
await asyncio.sleep(5)
def is_trading_active(self) -> bool:
"""Check if trading is active"""
return self.trading_active and self.state == WSOLState.IDLE
async def cleanup(self):
"""Cleanup resources"""
logger.info("Cleaning up SolanaCLI resources")
try:
self.thread_pool.shutdown(wait=True)
if torch.cuda.is_available():
torch.cuda.empty_cache()
logger.info("Cleanup completed")
except Exception as e:
logger.error(f"Cleanup error: {e}")
raise