How to Compile Solidity Smart Contracts With Python

Jordan Cassady
CoinsBench
Published in
1 min readFeb 25, 2022

--

If you’re just getting started with Solidity smart contract development, you might have tried the Remix IDE. It’s a super convenient way to write a contract in Solidity directly inside the browser. But what if you need to incorporate a smart contract into an existing Python project?

Brownie is a development & testing framework and includes many time saving features including .sol source file compilation and should definitely be considered. However, situations will arise where a simpler, lightweight approach makes the most sense.

Patrick Collins hosts a popular blockchain course covering all things Ethereum development, and specifically covers the below code snippet in depth on YouTube. You should definitely check it out!

But for now, let’s check out py-solc-x — a Python wrapper for the Solidity compiler. First, we need to call the solcx.install_solc() function with a version string (I used 0.6.6). Once the Solidity compiler has been installed, we can call the solcx.compile_standard() function to actually compile the contract code.

Note the compiler’s “outputSelection” setting contains options like “abi”, which will be useful if you need to call functions on the smart contract from Python once deployed on a test (or mainnet) blockchain.

The ABI can be accessed from within Python using the same JSON parsing syntax you might use when working with a RESTful API. And there we have it! Compile Ethereum smart contracts written in Solidity from a Python script with just a couple function calls, and you’re on your way.

--

--