CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-solc-x

Python wrapper and version management tool for the solc Solidity compiler.

77

1.05x

Evaluation77%

1.05x

Agent success when using this tile

Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

Comprehensive exception hierarchy for handling compilation errors, installation failures, version mismatches, and configuration issues. All exceptions provide detailed error information including command output and diagnostic data.

Capabilities

Core Exceptions

Base exception classes that provide detailed error information and diagnostic data for troubleshooting.

class SolcError(Exception):
    """
    Base exception for solc execution errors.
    
    Attributes:
    - message: Error description
    - command: Command that was executed
    - return_code: Process return code
    - stdin_data: Input data sent to process
    - stdout_data: Process stdout output  
    - stderr_data: Process stderr output
    - error_dict: Parsed error information (if available)
    """
    
    def __init__(
        self,
        message: Optional[str] = None,
        command: Optional[List[str]] = None,
        return_code: Optional[int] = None,
        stdin_data: Optional[str] = None,
        stdout_data: Optional[str] = None,
        stderr_data: Optional[str] = None,
        error_dict: Optional[Dict] = None,
    ) -> None: ...

class ContractsNotFound(SolcError):
    """
    Raised when no contracts found during compilation.
    
    This typically occurs when:
    - Source code contains no contract definitions
    - All contracts have compilation errors
    - Source files are empty or invalid
    """

Usage example:

import solcx
from solcx import SolcError, ContractsNotFound

try:
    # Invalid Solidity code
    result = solcx.compile_source("invalid code here")
except ContractsNotFound:
    print("No valid contracts found in source")
except SolcError as e:
    print(f"Compilation failed: {e.message}")
    print(f"Command: {' '.join(e.command)}")
    print(f"Return code: {e.return_code}")
    if e.stderr_data:
        print(f"Error output: {e.stderr_data}")

Installation Exceptions

Exceptions related to Solidity compiler installation, version management, and binary execution.

class SolcInstallationError(Exception):
    """
    Raised when solc installation fails.
    
    Common causes:
    - Network connectivity issues
    - Invalid version specifications
    - File system permissions
    - Corrupted downloads
    """

class SolcNotInstalled(Exception):
    """
    Raised when trying to use solc that isn't installed.
    
    This occurs when:
    - No solc versions are installed
    - Specified version is not installed
    - Installation directory is corrupted
    """

class UnexpectedVersionError(Exception):
    """
    Raised when installed solc version doesn't match expected version.
    
    This can happen when:
    - Downloaded binary has different version than requested
    - Binary is corrupted or modified
    - Version metadata is incorrect
    """

class UnsupportedVersionError(ValueError):
    """
    Raised when trying to use unsupported solc version.
    
    py-solc-x supports solc versions >= 0.4.11
    """

class DownloadError(Exception):
    """
    Raised when download fails during installation.
    
    Common causes:
    - Network connectivity issues
    - Server errors (404, 500, etc.)  
    - GitHub API rate limiting
    - Interrupted downloads
    """

Usage example:

import solcx
from solcx import (
    SolcNotInstalled, 
    SolcInstallationError, 
    UnsupportedVersionError,
    DownloadError
)

# Handle missing installation
try:
    solcx.set_solc_version('0.8.19')
except SolcNotInstalled:
    print("Version 0.8.19 not installed, installing now...")
    solcx.install_solc('0.8.19')
    solcx.set_solc_version('0.8.19')

# Handle installation failures
try:
    solcx.install_solc('0.8.99')  # Non-existent version
except SolcInstallationError as e:
    print(f"Installation failed: {e}")
except DownloadError as e:
    print(f"Download failed: {e}")

# Handle unsupported versions
try:
    solcx.install_solc('0.3.0')  # Too old
except UnsupportedVersionError as e:
    print(f"Version not supported: {e}")

Compiler Option Exceptions

Exceptions for invalid compiler options and values, helping identify compatibility issues between different solc versions.

class UnknownOption(AttributeError):
    """
    Raised when using unsupported solc option.
    
    Different solc versions support different command-line options.
    This helps identify when an option isn't available in the active version.
    """

class UnknownValue(ValueError):
    """
    Raised when using invalid value for solc option.
    
    This occurs when an option exists but the provided value is not valid
    for the current solc version.
    """

Usage example:

import solcx
from solcx import UnknownOption, UnknownValue

try:
    # This might fail with older solc versions
    solcx.compile_source(
        "pragma solidity ^0.4.0; contract Test {}",
        metadata_hash='ipfs'  # Not supported in very old versions
    )
except UnknownOption as e:
    print(f"Option not supported: {e}")
except UnknownValue as e:
    print(f"Invalid option value: {e}")

Warning Classes

Warning classes for non-fatal issues that don't prevent execution but may indicate problems.

class UnexpectedVersionWarning(Warning):
    """
    Warning for version mismatches that aren't fatal.
    
    This is raised when:
    - Installed binary version differs slightly from expected
    - Nightly builds are detected
    - Version metadata is ambiguous
    """

Usage example:

import warnings
import solcx
from solcx import UnexpectedVersionWarning

# Capture version warnings
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    
    # This might trigger a warning for nightly builds
    solcx.install_solc('0.8.19')
    
    for warning in w:
        if issubclass(warning.category, UnexpectedVersionWarning):
            print(f"Version warning: {warning.message}")

Exception Handling Patterns

Graceful Installation

Handle missing installations gracefully by automatically installing required versions:

import solcx
from solcx import SolcNotInstalled

def ensure_solc_version(version):
    """Ensure a specific solc version is available."""
    try:
        solcx.set_solc_version(version)
    except SolcNotInstalled:
        print(f"Installing solc {version}...")
        solcx.install_solc(version)
        solcx.set_solc_version(version)

# Usage
ensure_solc_version('0.8.19')

Compilation Error Analysis

Extract detailed error information from compilation failures:

import solcx
from solcx import SolcError

def compile_with_error_analysis(source):
    """Compile source with detailed error reporting."""
    try:
        return solcx.compile_source(source)
    except SolcError as e:
        print("Compilation failed!")
        print(f"Command: {' '.join(e.command)}")
        print(f"Return code: {e.return_code}")
        
        if e.stderr_data:
            # Parse and display specific errors
            error_lines = e.stderr_data.strip().split('\n')
            for line in error_lines:
                if 'Error:' in line or 'Warning:' in line:
                    print(f"  {line}")
        
        # Re-raise for caller to handle
        raise

# Usage
source = '''
pragma solidity ^0.8.0;
contract Test {
    uint256 invalid syntax here;
}
'''

try:
    compiled = compile_with_error_analysis(source)
except SolcError:
    print("Could not compile contract")

Version Compatibility Checking

Check compatibility before performing operations:

import solcx
from solcx import UnsupportedVersionError, UnknownOption
from packaging.version import Version

def compile_with_optimization(source, solc_version='0.8.19'):
    """Compile with optimization, handling version compatibility."""
    # Ensure version is available
    try:
        solcx.set_solc_version(solc_version)
    except:
        solcx.install_solc(solc_version)
        solcx.set_solc_version(solc_version)
    
    # Check if optimization is supported
    version_obj = Version(solc_version)
    
    try:
        if version_obj >= Version('0.5.0'):
            # Modern optimization options
            return solcx.compile_source(
                source,
                optimize=True,
                optimize_runs=200
            )
        else:
            # Basic optimization for older versions
            return solcx.compile_source(source, optimize=True)
            
    except UnknownOption as e:
        print(f"Optimization not available: {e}")
        # Fall back to basic compilation
        return solcx.compile_source(source)

# Usage
result = compile_with_optimization(
    "pragma solidity ^0.8.0; contract Test { uint256 public value = 42; }",
    '0.8.19'
)

Network Error Handling

Handle network-related errors during installation:

import time
import solcx
from solcx import DownloadError, SolcInstallationError

def install_solc_with_retry(version, max_retries=3):
    """Install solc with retry logic for network errors."""
    for attempt in range(max_retries):
        try:
            return solcx.install_solc(version)
        except DownloadError as e:
            if attempt == max_retries - 1:
                raise
            print(f"Download failed (attempt {attempt + 1}): {e}")
            print(f"Retrying in {2 ** attempt} seconds...")
            time.sleep(2 ** attempt)
        except SolcInstallationError as e:
            if "network" in str(e).lower() or "connection" in str(e).lower():
                if attempt == max_retries - 1:
                    raise
                print(f"Network error (attempt {attempt + 1}): {e}")
                time.sleep(2 ** attempt)
            else:
                # Non-network error, don't retry
                raise

# Usage
try:
    version = install_solc_with_retry('0.8.19')
    print(f"Successfully installed: {version}")
except Exception as e:
    print(f"Failed to install after retries: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-py-solc-x

docs

compilation.md

exceptions.md

index.md

version-management.md

tile.json