Py Solc X

2.0.5 · active · verified Fri Apr 17

py-solc-x is a Python wrapper and version management tool for the `solc` Solidity compiler. It simplifies the installation, management, and use of multiple `solc` versions, allowing developers to compile Solidity code directly from Python. The current version is 2.0.5, and it sees frequent minor updates for bug fixes and occasional feature releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install a specific `solc` version, set it as the active compiler, and then compile a simple Solidity contract source code using `py-solc-x`. It outputs the contract's ABI and bytecode.

import solcx
import os

solidity_code = '''
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 public storedData;

    constructor(uint256 initialData) {
        storedData = initialData;
    }

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint25n) {
        return storedData;
    }
}
'''

# Ensure a solc version is installed
# Using os.environ.get for an example, in real use specify a version like '0.8.10'
target_version = os.environ.get('SOLC_VERSION', '0.8.10')

if not solcx.get_installed_solc_versions():
    print(f"No solc versions found. Installing {target_version}...")
    solcx.install_solc(target_version)

# Select the desired solc version. This is crucial.
solcx.set_solc_version(target_version)
print(f"Using solc version: {solcx.get_solc_version()}")

# Compile the Solidity code
compiled_sol = solcx.compile_source(
    solidity_code,
    output_values=['abi', 'bin']
)

# Extract contract data
contract_name = '<stdin>:SimpleStorage'
contract_abi = compiled_sol[contract_name]['abi']
contract_bytecode = compiled_sol[contract_name]['bin']

print("\n--- Compiled Contract ABI ---")
print(contract_abi)
print("\n--- Compiled Contract Bytecode ---")
print(contract_bytecode[:60] + '...') # Print first 60 chars of bytecode for brevity

view raw JSON →