Python wrapper around the solc Solidity compiler
—
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.
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
"""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']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']
}
}
}
})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")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']
}
}
}
})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']}")Each source can be defined with either:
Optional compilation settings:
'settings': {
'optimizer': {
'enabled': bool,
'runs': int
},
'evmVersion': str, # 'homestead', 'tangerineWhistle', 'spuriousDragon', 'byzantium', etc.
'outputSelection': {
'file.sol': {
'ContractName': ['abi', 'evm.bytecode', 'metadata', ...]
}
}
}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 documentationThe 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