CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-solc

Python wrapper around the solc Solidity compiler

Pending
Overview
Eval results
Files

legacy-compilation.mddocs/

Legacy Combined JSON Compilation

Legacy compilation methods using the combined JSON output format, supporting older workflows and integrations. These methods are maintained for backward compatibility but new projects should prefer the standard JSON interface.

Capabilities

Source String Compilation

Compiles Solidity source code from a string using the legacy combined JSON output format.

def compile_source(source, allow_empty=False, output_values=ALL_OUTPUT_VALUES, **kwargs):
    """
    Compile Solidity source code from a string.

    Args:
        source (str): Solidity source code to compile
        allow_empty (bool): Whether to allow compilation with no contracts found
        output_values (tuple): Tuple of output values to include in compilation 
                               (default: ALL_OUTPUT_VALUES)
        **kwargs: Additional arguments passed to solc wrapper including:
            - import_remappings: List of import remapping strings
            - optimize: Enable optimization
            - optimize_runs: Number of optimization runs
            - allow_paths: Allowed import paths

    Returns:
        dict: Dictionary of compiled contracts with contract names as keys, each containing:
            - abi: Contract application binary interface (list)
            - code: Contract creation bytecode (hex string)
            - code_runtime: Contract runtime bytecode (hex string)
            - source: Source code (if 'source' in output_values)
            - meta: Compilation metadata

    Raises:
        ContractsNotFound: When no contracts found and allow_empty=False
        SolcError: When compilation fails
    """

Source Files Compilation

Compiles Solidity source files using the legacy combined JSON output format.

def compile_files(source_files, allow_empty=False, output_values=ALL_OUTPUT_VALUES, **kwargs):
    """
    Compile Solidity source files.

    Args:
        source_files (list): List of source file paths to compile
        allow_empty (bool): Whether to allow compilation with no contracts found
        output_values (tuple): Tuple of output values to include in compilation
                               (default: ALL_OUTPUT_VALUES)
        **kwargs: Additional arguments passed to solc wrapper

    Returns:
        dict: Dictionary of compiled contracts with same structure as compile_source

    Raises:
        ContractsNotFound: When no contracts found and allow_empty=False
        SolcError: When compilation fails
    """

Constants

ALL_OUTPUT_VALUES

ALL_OUTPUT_VALUES = (
    "abi", 
    "asm", 
    "ast", 
    "bin", 
    "bin-runtime", 
    "clone-bin", 
    "devdoc", 
    "interface", 
    "opcodes", 
    "userdoc"
)

Default tuple of output values included in legacy compilation. You can specify a subset of these values to reduce compilation time and output size.

Usage Examples

Basic Source String Compilation

from solc import compile_source

# Compile simple contract from string
source_code = '''
pragma solidity ^0.4.24;

contract SimpleStorage {
    uint256 public storedData;
    
    constructor(uint256 initialValue) public {
        storedData = initialValue;
    }
    
    function set(uint256 x) public {
        storedData = x;
    }
    
    function get() public view returns (uint256) {
        return storedData;
    }
}
'''

compiled = compile_source(source_code)

# Access contract data
contract = compiled['SimpleStorage']
abi = contract['abi']
bytecode = contract['code']
runtime_bytecode = contract['code_runtime']

print(f"Contract ABI: {abi}")
print(f"Bytecode: {bytecode}")

File Compilation

from solc import compile_files

# Compile contracts from files
compiled = compile_files([
    '/path/to/contracts/Token.sol',
    '/path/to/contracts/Crowdsale.sol'
])

# Access compiled contracts
for contract_name, contract_data in compiled.items():
    print(f"Contract: {contract_name}")
    print(f"ABI: {contract_data['abi']}")
    print(f"Bytecode length: {len(contract_data['code'])}")

Selective Output Values

from solc import compile_source

# Only compile ABI and bytecode (faster)
compiled = compile_source(
    source_code,
    output_values=("abi", "bin", "bin-runtime")
)

# Only these keys will be present in the output
contract = compiled['MyContract']
abi = contract['abi']
creation_code = contract['code']
runtime_code = contract['code_runtime']
# contract['ast'] would not be available

Compilation with Import Remappings

from solc import compile_files

# Compile with import remappings for cleaner imports
compiled = compile_files(
    ['/path/to/my/Contract.sol'],
    import_remappings=[
        "openzeppelin-solidity=/path/to/node_modules/openzeppelin-solidity",
        "my-lib=/path/to/my/libraries"
    ]
)

Optimized Compilation

from solc import compile_source

# Compile with optimization enabled
compiled = compile_source(
    source_code,
    optimize=True,
    optimize_runs=200
)

# The resulting bytecode will be optimized
optimized_contract = compiled['MyContract']
optimized_bytecode = optimized_contract['code']

Multiple Contracts in One Source

from solc import compile_source

# Source with multiple contracts
multi_contract_source = '''
pragma solidity ^0.4.24;

contract Math {
    function add(uint a, uint b) public pure returns (uint) {
        return a + b;
    }
}

contract Calculator {
    Math private math;
    
    constructor(address mathAddress) public {
        math = Math(mathAddress);
    }
    
    function calculate(uint x, uint y) public view returns (uint) {
        return math.add(x, y);
    }
}
'''

compiled = compile_source(multi_contract_source)

# Both contracts are available
math_contract = compiled['Math']
calculator_contract = compiled['Calculator']

print(f"Math ABI: {math_contract['abi']}")
print(f"Calculator ABI: {calculator_contract['abi']}")

Error Handling with Legacy Compilation

from solc import compile_source, SolcError, ContractsNotFound

try:
    # This will fail due to syntax error
    broken_source = '''
        pragma solidity ^0.4.24;
        contract Broken {
            uint256 value = ; // Syntax error
        }
    '''
    
    compiled = compile_source(broken_source)
    
except SolcError as e:
    print(f"Compilation error: {e}")
    print(f"Return code: {e.return_code}")
    print(f"Stderr: {e.stderr_data}")
    
except ContractsNotFound as e:
    print("No contracts found in source code")

Allow Empty Compilation

from solc import compile_source

# Source with no contracts (only imports/libraries)
empty_source = '''
pragma solidity ^0.4.24;

// Just a comment, no contracts
'''

try:
    # This would normally raise ContractsNotFound
    compiled = compile_source(empty_source, allow_empty=True)
    print("Compilation successful, but no contracts found")
    print(f"Result: {compiled}")  # Will be an empty dict
    
except ContractsNotFound:
    print("This won't be reached because allow_empty=True")

Output Format

The legacy combined JSON format returns a dictionary where:

  • Keys: Contract names (e.g., 'MyContract')
  • Values: Contract compilation data dictionaries

Each contract data dictionary contains:

{
    'abi': [
        {
            'type': 'function',
            'name': 'myFunction',
            'inputs': [...],
            'outputs': [...],
            'stateMutability': 'view'
        },
        # ... more ABI entries
    ],
    'code': '0x608060405234801561001057600080fd5b50...',  # Creation bytecode
    'code_runtime': '0x608060405260043610610041576000357c01...',  # Runtime bytecode
    'meta': {
        'compilerVersion': '0.4.24+commit.e67f0147.Linux.g++',
        'language': 'Solidity',
        'languageVersion': '0'
    },
    'ast': {...},  # Abstract Syntax Tree (if requested)
    'asm': '...',  # Assembly code (if requested)
    'devdoc': {...},  # Developer documentation (if requested)
    'userdoc': {...}  # User documentation (if requested)
}

Comparison with Standard JSON

FeatureLegacy Combined JSONStandard JSON
Input FormatString/Files + optionsStructured JSON object
Output FormatFlat contract dictionaryNested structure by file
Error HandlingException-basedErrors in output object
FlexibilityLimited output controlFull compilation control
Recommended UseLegacy compatibilityNew projects

Install with Tessl CLI

npx tessl i tessl/pypi-py-solc

docs

exceptions.md

index.md

installation.md

legacy-compilation.md

standard-json-compilation.md

tile.json