Python and Blockchain Basics (Ganache, Web3, Python Environment)
The journey of a thousand miles begins with the first step...
Welcome to our Python blockchain journey :)
In this series of short tutorials, i will publish some example codes on how to do exiting stuff on the blockchain, especially in the DEFI sector, with Python. I will write short sentences and focus more on code during this series and will try to skip most stuff, you find elsewhere.
I am not a native speaker, but Python code is an universal language. So we focus on that.
This short intro is really just to give you an overview, some keywords for further research and get you started.
Why Python you may ask?
It is a great and easy to learn programming language with good support of everything we need.
Python Basics
If you’re unfamiliar with Python so far. I recommend you to learn at least some basics. I know you want to do cool blockchain stuff and so do i. But it makes things a lot easier, if you have at least a basic understanding of the language, before you start.
Here are some good free resources to start with:
A Byte of Python ( https://python.swaroopch.com/ )
Non Programmers Tutorial for Python 3 ( https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3 )
Python 101 ( https://python101.pythonlibrary.org/ )
Choose one of them and learn the basics.
Also a great resource for learning Programming might be ChatGPT. It sometimes gets things wrong, but you can paste in a code and get a good explanation or ask it, how to do things. Just make sure, you understand the output.
Hint: don’t spend to much time on learning theory. You will learn much more by doing. So just go over the basics briefly, write a few lines of code, and learn the rest on the way.
The Development Environment
As a code editor i use Visual Studio Code ( https://code.visualstudio.com/ ). Really an amazing tool. But you can use whatever suits you. Pycharm might be a good alternative and basically any editor works.
Operating System
I use Debian Linux, but can recommend any Linux environment like Ubuntu.
OS X is fine as well, there is a Unix under the hood, so everything should work out of the box most of the time.
If you’re using Windows, thats fine as well. I recommend checking out Windows Subsystem for Linux, which gives you a fully working terminal and a Linux Environment.
Local Test Blockchain
To test all this things, without losing money, i recommend using a local test blockchain.
I use ganache-cli:
https://github.com/trufflesuite/ganache
It’s easy to use and works most of the time.
Make sure to setup your test chain and that you can connect to localhost:8545. We will work a lot with Ganache during this series.
I start ganache with this command:
ganache — accounts 10 -k london — fork <RPC_URL> — gasLimit 120000000 — port 8545 -m ‘photo agree until citizen chair peace struggle act achieve oven twist truly’
You have to replace RPC_URL with a RPC endpoint of your choice. You can get a free one at Infura for example. This command creates a local fork of the blockchain, which means, you can do everything in a local enviroment without costs but still have access to all smart contracts and transactions which happened until the moment of the fork.
It gives you 10 test accounts with 1.000 Ether to play with. I usually supply also the seedphrase, so i always get the same accounts. You can use the given one as well, or chose your own.
Hint: For Debian / Linux users, make sure to use nvm version 16. Newer or older ones might give you some SSL header errors. ( Now using node v16.15.1 (npm v8.11.0) )
The Python Environment
I will be using Python 3.10+ for everything. (currently 3.11)
It’s a good practice to setup a virtual environment first and install everything there.
python -m venv defienv
source defienv/bin/activate.
Hint: always make sure, to work within your virtual environment and that it’s activated.
You can read more about virtual environments here:
https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/
When you have you virtual enviroment setup, make sure to install the web3 package, which we will be using during most of our tutorials.
I am using pip as a package manager, because it is the easiest.
So in your enviroment type:
pip install web3
And now you’re good to go. You just installed the amazing web3 Python package which gives you access to the wonderful world of the blockchains.
With some of the tutorials, there will be a file called requirements.txt
To save all the packages you installed you can use the freeze command, that way you can restore it on any other computer or install all the packages you need for a tutorials with a single command.
pip freeze > requirements.txt
This writes all installed packages and dependencies into the requirements.txt file.
In some of the tutorials, you will find such a file, you can easily import it with:
pip install -r requirements.txt
Your first blockchain command
Now start a Python shell and type:
Python 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>> from web3 import Web3
>>> w3 = Web3(Web3.HTTPProvider(‘http://localhost:8545'))
>>> print(f”latest local ganache block: {w3.eth.get_block(‘latest’)}”)
latest local ganache block: AttributeDict({‘hash’: HexBytes(‘0x0fd35a90f3940009277256fa7e74f92f16d835f90be96a750e5402fe01ef5b6f’), ‘parentHash’: HexBytes(‘0xc2203b058ec7fab92ec70ab716f665fdf5799175b2e5c312a7001431f0e58080’), ‘sha3Uncles’: HexBytes(‘0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347’), ‘miner’: ‘0x0000000000000000000000000000000000000000’, ‘stateRoot’: HexBytes(‘0x7d369847ed80953d3805232efd873a42dc626c82b2d3d39db7752f85e240cd26’), ‘transactionsRoot’: HexBytes(‘0x82031e30e85f586b998576765777c3e8bf3efcc2bf44586ece0d76ef2d257a0a’), ‘receiptsRoot’: HexBytes(‘0x4b936c2f56a132015a57a34c6a9bf29f13de04aa4cd9e7c75aa97dba8ab7a755’), ‘logsBloom’: HexBytes(‘0x00210000000000000000000080000000000000000000000000000000000000000000000000000000400000000000010002010000080000000000000000080000000000080000000000000008000000200000000000000000000000400060000000000000000000000000000200000000000000200000000000000010000000000800804000000000000000000000000000000000000000080000004000100000000000000000000000000080000000000400000000000000000000000000004000000002000000000000000000000000000000020000001000100000000000000000200004000000000004000000000000001000000000000000000000000400’), ‘difficulty’: 1, ‘number’: 17937464, ‘gasLimit’: 120000000, ‘gasUsed’: 165857, ‘timestamp’: 1692310745, ‘extraData’: HexBytes(‘0x’), ‘mixHash’: HexBytes(‘0x0000000000000000000000000000000000000000000000000000000000000000’), ‘nonce’: HexBytes(‘0x0000000000000000’), ‘totalDifficulty’: 58750003716598352816473, ‘baseFeePerGas’: 99606287599, ‘size’: 1575, ‘transactions’: [HexBytes(‘0x5b9cfa8cd2e2c609efffaceab8a8be7569e03fed11a8eddb079915fa993735ac’)], ‘uncles’: [], ‘withdrawals’: []})
Amazing, we just got the latest block, our first Python blockchain interaction with just 3 lines of code.
That’s it. When you got this setup working, you can follow along the rest. I might expand this from time to time if questions arise or add a FAQ.
Some great Python & Blockchain development resources
Solidity, Blockchain and Smart Contract Course — Beginner to Expert Python (
)
Patrick Collins does an amazing job here. Even if you don’t want to write smart contracts, make sure, to check this out.
https://realpython.com/
— they have really good in depth articles about nearly everything.