--- alwaysApply: true --- # Python Code Style Rules ## Formatting Standards ### Ruff Configuration Compliance - Use 88 character line length limit - Use 4 spaces for indentation (never tabs) - Use double quotes for strings consistently - Target Python 3.11+ features and syntax - Enable automatic import sorting and organization ### Import Organization ```python # Standard library imports first import asyncio import logging from pathlib import Path # Third-party imports second import aiohttp from solana.rpc.async_api import AsyncClient # Local imports last from config_loader import load_bot_config from utils.logger import get_logger ``` ### Type Annotations - Add type hints to ALL public functions and methods - Use modern typing syntax (Python 3.9+ union syntax where applicable) - Include return type annotations - Use `from typing import Any` for complex types ```python def process_transaction(tx_data: dict[str, Any]) -> bool: """Process transaction data and return success status.""" pass async def fetch_data(endpoint: str) -> dict[str, Any] | None: """Fetch data from endpoint, return None on failure.""" pass ``` ## Documentation Standards ### Docstring Format Use Google-style docstrings for all functions and classes: ```python def calculate_slippage(amount: float, slippage_percent: float) -> float: """Calculate slippage amount for a trade. Args: amount: The trade amount in SOL slippage_percent: Slippage percentage (0.1 = 10%) Returns: The calculated slippage amount Raises: ValueError: If slippage_percent is negative """ if slippage_percent < 0: raise ValueError("Slippage percentage cannot be negative") return amount * slippage_percent ``` ## Error Handling ### Comprehensive Exception Handling - Use try-catch blocks for all external operations (RPC calls, file I/O) - Log exceptions with context using `logging.exception()` - Provide meaningful error messages - Don't suppress exceptions without good reason ```python try: result = await client.get_account_info(address) logger.info(f"Successfully fetched account info for {address}") except Exception as e: logger.exception(f"Failed to fetch account info for {address}: {e}") raise ``` ## Logging Standards ### Logger Usage - Use `get_logger(__name__)` pattern consistently - Import from `utils.logger` - Use appropriate log levels (DEBUG, INFO, WARNING, ERROR) - Include context in log messages ```python from utils.logger import get_logger logger = get_logger(__name__) # Good logging examples logger.info(f"Starting bot '{bot_name}' with platform {platform.value}") logger.warning(f"Transaction failed, attempt {attempt}/{max_attempts}") logger.error(f"Platform {platform.value} is not supported") ``` ## Security Rules ### Sensitive Data - NEVER hardcode private keys, API tokens, or secrets - Use environment variables for all sensitive configuration - Don't log sensitive information - Validate all external inputs ### Safe Practices ```python # Good - using environment variables private_key = os.getenv("SOLANA_PRIVATE_KEY") if not private_key: raise ValueError("SOLANA_PRIVATE_KEY environment variable is required") # Bad - hardcoded secrets private_key = "your_secret_key_here" # NEVER DO THIS ``` ## Code Quality ### Linting Compliance Ensure code passes all enabled Ruff rules: - Security best practices (S) - Type annotations (ANN) - Exception handling (BLE, TRY) - Code complexity (C90) - Pylint conventions (PL) - No commented-out code (ERA) ### Performance Considerations - Use async/await for I/O operations - Implement proper connection pooling for HTTP clients - Cache expensive computations when appropriate - Use uvloop for better async performance ```python # Set uvloop policy at module level import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) ```