|
| 1 | +"""Solana environment configuration validation.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import os |
| 6 | +import logging |
| 7 | +from typing import Any, Optional |
| 8 | + |
| 9 | +from pydantic import BaseModel, Field, ValidationError, model_validator, ConfigDict |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class SolanaConfig(BaseModel): |
| 15 | + """Validated configuration required for Solana toolkit operations.""" |
| 16 | + |
| 17 | + wallet_secret_salt: Optional[str] = Field(default=None, alias="WALLET_SECRET_SALT") |
| 18 | + wallet_secret_key: Optional[str] = Field(default=None, alias="WALLET_SECRET_KEY") |
| 19 | + wallet_public_key: Optional[str] = Field(default=None, alias="WALLET_PUBLIC_KEY") |
| 20 | + |
| 21 | + sol_address: str = Field(alias="SOL_ADDRESS") |
| 22 | + slippage: str = Field(alias="SLIPPAGE") |
| 23 | + solana_rpc_url: str = Field(alias="SOLANA_RPC_URL") |
| 24 | + helius_api_key: str = Field(alias="HELIUS_API_KEY") |
| 25 | + birdeye_api_key: str = Field(alias="BIRDEYE_API_KEY") |
| 26 | + |
| 27 | + model_config = ConfigDict(populate_by_name=True, extra="forbid") |
| 28 | + |
| 29 | + @model_validator(mode="after") |
| 30 | + def _validate_key_material(cls, values: "SolanaConfig") -> "SolanaConfig": |
| 31 | + """Ensure either a secret salt or keypair credentials are present.""" |
| 32 | + has_salt = bool(values.wallet_secret_salt) |
| 33 | + has_keypair = bool(values.wallet_secret_key and values.wallet_public_key) |
| 34 | + |
| 35 | + if not (has_salt or has_keypair): |
| 36 | + raise ValueError( |
| 37 | + "Provide WALLET_SECRET_SALT or both WALLET_SECRET_KEY and WALLET_PUBLIC_KEY." |
| 38 | + ) |
| 39 | + return values |
| 40 | + |
| 41 | + |
| 42 | +def _runtime_get(runtime: Any, key: str) -> Optional[str]: |
| 43 | + """Attempt to read a setting from a runtime object if available.""" |
| 44 | + if runtime is None: |
| 45 | + return None |
| 46 | + |
| 47 | + for attr in ("get_setting", "getSetting", "get"): |
| 48 | + getter = getattr(runtime, attr, None) |
| 49 | + if callable(getter): |
| 50 | + try: |
| 51 | + value = getter(key) |
| 52 | + except TypeError: |
| 53 | + # Getter signature mismatch – try next option |
| 54 | + continue |
| 55 | + if value is not None: |
| 56 | + return value |
| 57 | + |
| 58 | + # Common pattern: runtime.settings dict |
| 59 | + settings = getattr(runtime, "settings", None) |
| 60 | + if isinstance(settings, dict): |
| 61 | + return settings.get(key) |
| 62 | + |
| 63 | + return None |
| 64 | + |
| 65 | + |
| 66 | +def _read_config_value(runtime: Any, *keys: str) -> Optional[str]: |
| 67 | + """Return the first non-empty value from runtime or environment for the provided keys.""" |
| 68 | + for key in keys: |
| 69 | + value = _runtime_get(runtime, key) |
| 70 | + if value is None: |
| 71 | + value = os.getenv(key) |
| 72 | + |
| 73 | + if isinstance(value, str): |
| 74 | + value = value.strip() |
| 75 | + |
| 76 | + if value: |
| 77 | + return value |
| 78 | + |
| 79 | + return None |
| 80 | + |
| 81 | + |
| 82 | +def load_solana_config(runtime: Any = None) -> SolanaConfig: |
| 83 | + """Validate and return Solana configuration based on runtime settings and environment variables. |
| 84 | +
|
| 85 | + Args: |
| 86 | + runtime: Optional runtime object providing a ``get_setting``-style API. |
| 87 | +
|
| 88 | + Returns: |
| 89 | + SolanaConfig: Validated configuration object. |
| 90 | +
|
| 91 | + Raises: |
| 92 | + ValueError: When validation fails or required fields are missing. |
| 93 | + """ |
| 94 | + config_payload = { |
| 95 | + "WALLET_SECRET_SALT": _read_config_value(runtime, "WALLET_SECRET_SALT"), |
| 96 | + "WALLET_SECRET_KEY": _read_config_value(runtime, "WALLET_SECRET_KEY"), |
| 97 | + "WALLET_PUBLIC_KEY": _read_config_value( |
| 98 | + runtime, |
| 99 | + "SOLANA_PUBLIC_KEY", |
| 100 | + "WALLET_PUBLIC_KEY", |
| 101 | + ), |
| 102 | + "SOL_ADDRESS": _read_config_value(runtime, "SOL_ADDRESS"), |
| 103 | + "SLIPPAGE": _read_config_value(runtime, "SLIPPAGE"), |
| 104 | + "SOLANA_RPC_URL": _read_config_value(runtime, "SOLANA_RPC_URL"), |
| 105 | + "HELIUS_API_KEY": _read_config_value(runtime, "HELIUS_API_KEY"), |
| 106 | + "BIRDEYE_API_KEY": _read_config_value(runtime, "BIRDEYE_API_KEY"), |
| 107 | + } |
| 108 | + |
| 109 | + try: |
| 110 | + return SolanaConfig(**config_payload) |
| 111 | + except ValidationError as exc: |
| 112 | + messages = [] |
| 113 | + for error in exc.errors(): |
| 114 | + location = ".".join(str(part) for part in error.get("loc", ())) |
| 115 | + messages.append(f"{location or 'configuration'}: {error.get('msg')}") |
| 116 | + |
| 117 | + detail = "\n".join(messages) or str(exc) |
| 118 | + logger.error("Solana configuration validation failed:\n%s", detail) |
| 119 | + raise ValueError(f"Solana configuration validation failed:\n{detail}") from exc |
| 120 | + |
0 commit comments