CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-solc

Python wrapper around the solc Solidity compiler

Pending
Overview
Eval results
Files

standard-json-compilation.mddocs/

Standard JSON Compilation

Modern compilation interface providing comprehensive control over compilation settings and outputs, supporting the Solidity standard JSON format. This is the recommended approach for new projects as it provides better error handling and more flexibility.

Capabilities

Standard JSON Compilation

Compiles Solidity using the standard JSON interface, which provides comprehensive control over compilation settings and outputs.

def compile_standard(input_data, allow_empty=False, **kwargs):
    """
    Compile using Solidity standard JSON interface.

    Args:
        input_data (dict): Standard JSON input data for compilation containing:
            - language: Must be 'Solidity'
            - sources: Dict mapping filenames to source content or urls
            - settings: Compilation settings including outputSelection
        allow_empty (bool): Whether to allow compilation with no contracts found
        **kwargs: Additional arguments passed to solc wrapper including:
            - solc_binary: Path to solc executable
            - allow_paths: Allowed import paths

    Returns:
        dict: Standard JSON compilation output containing:
            - contracts: Compiled contract data organized by source file and contract name
            - sources: Source file metadata and AST information  
            - errors: Compilation errors and warnings (if any)

    Raises:
        ContractsNotFound: When no contracts found and allow_empty=False
        SolcError: When compilation fails due to syntax errors or other issues
    """

Usage Examples

Basic Standard JSON Compilation

from solc import compile_standard

# Basic compilation with content
result = compile_standard({
    'language': 'Solidity',
    'sources': {
        'SimpleContract.sol': {
            'content': '''
                pragma solidity ^0.4.24;
                contract SimpleContract {
                    uint256 public value;
                    
                    function setValue(uint256 _value) public {
                        value = _value;
                    }
                    
                    function getValue() public view returns (uint256) {
                        return value;
                    }
                }
            '''
        }
    },
    'settings': {
        'outputSelection': {
            '*': {
                '*': ['abi', 'evm.bytecode', 'evm.bytecode.sourceMap']
            }
        }
    }
})

# Access compiled contract
contract_data = result['contracts']['SimpleContract.sol']['SimpleContract']
abi = contract_data['abi']
bytecode = contract_data['evm']['bytecode']['object']

Compilation with Multiple Files

from solc import compile_standard

# Compile multiple contracts
result = compile_standard({
    'language': 'Solidity',
    'sources': {
        'Token.sol': {
            'content': '''
                pragma solidity ^0.4.24;
                import "./SafeMath.sol";
                contract Token {
                    using SafeMath for uint256;
                    mapping(address => uint256) public balances;
                }
            '''
        },
        'SafeMath.sol': {
            'content': '''
                pragma solidity ^0.4.24;
                library SafeMath {
                    function add(uint256 a, uint256 b) internal pure returns (uint256) {
                        uint256 c = a + b;
                        require(c >= a, "SafeMath: addition overflow");
                        return c;
                    }
                }
            '''
        }
    },
    'settings': {
        'outputSelection': {
            '*': {
                '*': ['abi', 'evm.bytecode.object', 'metadata']
            }
        }
    }
})

Compilation from File URLs

from solc import compile_standard

# Compile from file paths
result = compile_standard({
    'language': 'Solidity',
    'sources': {
        'MyContract.sol': {
            'urls': ['/path/to/contracts/MyContract.sol']
        }
    },
    'settings': {
        'outputSelection': {
            '*': {
                '*': ['abi', 'evm.bytecode']
            }
        }
    }
}, allow_paths="/path/to/contracts")

Advanced Compilation Settings

from solc import compile_standard

# Compilation with optimization and custom EVM version
result = compile_standard({
    'language': 'Solidity',
    'sources': {
        'OptimizedContract.sol': {
            'content': '''
                pragma solidity ^0.4.24;
                contract OptimizedContract {
                    function complexCalculation(uint256 x) public pure returns (uint256) {
                        return (x * x * x) + (x * x) + x + 1;
                    }
                }
            '''
        }
    },
    'settings': {
        'optimizer': {
            'enabled': True,
            'runs': 200
        },
        'evmVersion': 'byzantium',
        'outputSelection': {
            '*': {
                '*': ['abi', 'evm.bytecode', 'evm.deployedBytecode', 'evm.gasEstimates']
            }
        }
    }
})

Error Handling

from solc import compile_standard, SolcError

try:
    result = compile_standard({
        'language': 'Solidity',
        'sources': {
            'BrokenContract.sol': {
                'content': '''
                    pragma solidity ^0.4.24;
                    contract BrokenContract {
                        // Syntax error: missing semicolon
                        uint256 public value = 42
                    }
                '''
            }
        },
        'settings': {
            'outputSelection': {
                '*': {
                    '*': ['abi', 'evm.bytecode']
                }
            }
        }
    })
except SolcError as e:
    print(f"Compilation failed: {e}")
    # Error details are available in the exception
    if hasattr(e, 'stdout_data'):
        import json
        error_output = json.loads(e.stdout_data)
        for error in error_output.get('errors', []):
            print(f"Error: {error['formattedMessage']}")

Input Format Specification

Required Fields

  • language: Must be 'Solidity'
  • sources: Dictionary mapping source file names to source definitions

Source Definitions

Each source can be defined with either:

  • content: Inline source code as string
  • urls: Array of file paths or URLs to source files

Settings Object

Optional compilation settings:

'settings': {
    'optimizer': {
        'enabled': bool,
        'runs': int
    },
    'evmVersion': str,  # 'homestead', 'tangerineWhistle', 'spuriousDragon', 'byzantium', etc.
    'outputSelection': {
        'file.sol': {
            'ContractName': ['abi', 'evm.bytecode', 'metadata', ...]
        }
    }
}

Output Selection Options

Available output values for outputSelection:

  • 'abi': Application Binary Interface
  • 'metadata': Contract metadata
  • 'evm.bytecode': Creation bytecode
  • 'evm.deployedBytecode': Runtime bytecode
  • 'evm.gasEstimates': Gas usage estimates
  • 'evm.methodIdentifiers': Method signature hashes
  • 'evm.assembly': Assembly output
  • 'devdoc': Developer documentation
  • 'userdoc': User documentation

Output Format

The standard JSON output contains:

{
    'contracts': {
        'source_file.sol': {
            'ContractName': {
                'abi': [...],
                'metadata': '...',
                'evm': {
                    'bytecode': {
                        'object': '0x...',
                        'sourceMap': '...'
                    },
                    'deployedBytecode': {...},
                    'gasEstimates': {...}
                }
            }
        }
    },
    'sources': {
        'source_file.sol': {
            'id': 0,
            'ast': {...}
        }
    },
    'errors': [
        {
            'type': 'Warning',
            'component': 'general',
            'severity': 'warning',
            'message': '...',
            'formattedMessage': '...'
        }
    ]
}

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