Today we will learn the basics of Web 3.0 and methods of interacting with it. We will explain how to do all operations with an Ethereum Blockchain and Web3.py, a software that allows working with Ethereum using Python.
And, of course, we will explain how to operate with an Ethereum Blockchain and set it up. This guide will provide you with the most useful information if you are familiar with the following tips and skills:
Now we can start our Python Web3 guide!
The term of 'Web 3.0' was used by Gavin Wood, Ethereum co-founder, soon after Ethereum was born in 2014. He mentioned that the previous versions of Web demanded too much from the users in the terms of trust and security and we have to move forward to solve this things. While previous concepts focused on human-machine interactions, this one talks more about system-to-system interaction where human just harvests the results of such an interaction.
Web 3.0 helps to eliminate data ownership problems. While the 2.0 information is centralized and controllable, the new era is more about independence. It stands on the idea of a decentralized, safe, and simply verifiable web. Creators expect to achieve that by removing a third party, which is not always trusted enough, and relying on system-to-system data exchange. It requires developing highly interoperable algorithms and ecosystems.
As a result, we get a large platform for a fair and independent user experience. It becomes possible with algorithms for verifying data and building applications in a completely new way. With the new technologies, users can control the amount of information they give and receive. It leads us closer to the concept of an open web, where developers can create safe, decentralized apps with upgraded security.
Secure transactions allow users to own and work with their data, while networking becomes just data connectors. The data connection is available in a decentralized way with protocols running on smart contracts.
The full terminology is available on the Web3 Foundation website.
It is a library that allows Ethereum Python interactions. It developed from Web3.js but was soon recomposed due to the higher popularity of Python compared to JavaScript among developers.
Web3.py allows a creation of decentralized apps (DApps). The library is full of tools for sending transactions, smart contract interactions, reading block data, and performing other tasks.
Today we will show basic actions and templates for interacting with the Ethereum Blockchain by applying Web3.py. With these functions, you will be able to build DApps further.
Check out this guide on DApp development for intermediate developers. This technology is still evolving, and developers discover its possibilities in solving different tasks. On the Ethereum website, you can always find freshly made DAapps that might inspire your development.
Ethereum is much more than a blockchain today, thanks to inventive community that developed and widened its possibilities since 2014. One of thousands of complement technologies, Web3.py becomes a library for connecting to nodes but it does not provide a node itself.
That is why you have to consider a data storage additionally. Your node will constantly update and exchange data with other nodes, so this information will require space to be stored. A node is your key to current state of the blockchain, and without it not much of the net will be useful.
The choice of a node depends on your personal preferences and possible needs. While choosing, remember two main types of nodes.
The second type is preferable for ones who have just come to an Ethereum blockchain and still don’t have serious plans for applying it. We recommend choosing hosted notes for the first time on Python Ethereum. In the Web3.py documentation, you will find recommendations on working with both local and hosted nodes.
The third solution is to apply a Blockchain API, like RPC Fast. This SaaS solution gives you freedom from third-party participants and saves time on extra work. As far as creating a local node from scratch is long and complicated, a significantly easier solution was invented.
We suggest you the RPC Fast API as the most versatile and multifunctional one. Remote Procedure Call is a protocol that allows programs to send service requests to other programs without diving deep into the program details. Currently, RPC Fast API operates on the following blockchains:
An API provides you with an endpoint to access the data in the blockchain. The algorithm contains only a couple of actions. RPC API takes an URL and sets it into the app configuration. It lets all processes run fast and without bugs.
The current function range involves:
It is a developing solution from Dysnix, a football team-sized DevOps team with huge experience in blockchain. Soon this API will be available for Avalanche, Polkadot, Solano, and other blockchains.
If you decided to do everything by yourself, please check whether you have the last version of Python installed on your computer and that you have a local or hosted node too. If you still want to create a local node from scratch, use trusted Geth or Parity platforms. Look for lessons on creating personal nodes on their websites.
We will give today’s examples on the RPC Fast-hosted node. It is one of the most popular and trusted nodes for Ethereum Python. Register to get a free account. It will be enough to start and test.
You can connect to your node via one of the following methods:
To start working, you should create an RPC Fast account and start a new project on the dashboard. On the project tab, you’ll see information about its status, the number of requests, endpoints, and security issues. Then you choose the endpoint, and an URL appears on the dashboard.
Web3.py comes with a set of basic providers:
Also, there are two experimental providers, EthereumTesterProvider and AsyncHTTPProvider. You can find a detailed explanation of their features in web3.py documentation. A single provider connection is usually enough for a basic case like ours and other scenarios. Still, creating a few examples of connections with multiple providers is available.
For more information on selecting a node, read a relatable part of Web3.py documentation. Here creators give pros and cons of each kind and examples of appliances.
Let’s try some web3 Python Ethereum interactions via the library. During this operation, we will use an HTTP connection. Checking the balance is the easiest activity to start from. Your first action is firing Python up in that way:
$ python
The next step is web3.py import:
from web3 import Web3
Are there any unclear aspects? Check the short YouTube course of explanations by DApp University to see how these operations function in a process.
Ethereum is not just a blockchain developing platform, and it includes a blockchain-based cryptocurrency. With an Ether Wallet, you can pay, get donations, and do other actions. To understand how Web3 Python works, let’s learn some basic operations with wallets.
Now you can check the account balance within a single action. To get it done, we will use the function web3.eth.getBalance. Also, you’ll need the Ether wallet number. Firstly, name the variable:
account = "your_wallet_number"
After that, let’s try checking the balance with the following request:
balance = web3.eth.getBalance ("your_wallet_number")
Finally, you should return a variable to receive an answer to your question. For your comfort, you can convert Wei to Ether. Wei is related to Ether as a penny to dollars but with a greater difference. It will be easier to look up the balance in the usual size:
print(web3.fromWei(balance, "ether"))
Now you know how to do balance check-ups on Python Web3! Other actions with wallets, such as finding transaction receipts, are available in the Web3 Documentation. Read some examples from there to understand the code better. Let’s move on and discover other options.
Smart contracts are an essential part of Ethereum Blockchain. In general, it is a composition of functions that control the state of data related to a certain address name. Just like the user’s account, a smart contract has an address, which means that it is open for transactions. Unlike a regular user account, a smart contract is programmed, and it will run only according to the program.
Smart contracts can exist under the following conditions:
Usually, you pay some money to create a smart contract because it requires storage and calculations. Many instruments allow interaction with contracts, such as Remix or Hardhat. We won’t use them today and apply only to the contract’s address. It will be enough to see how function inputs operate.
To start with, let’s try recalling data from a contract. For any interaction, we will need to know the abstract binary interface (ABI) and the address of a smart contract. In this operation, we won’t create a new contract, as it is a long and complicated process. You can look up useful information in the Python Ethereum and Web3 tutorials.
Let’s find out about the contract’s statement and start with defining variables:
address = 'YOUR_CONTRACT_ADDRESS'
abi = 'YOUR_CONTRACT_ABI'
To recall the total supply of a contract, type function totalSupply(). Results will appear in the following way:
contract_instance = w3.eth.contract(address=address, abi=abi)
result = contract_instance.functions.totalSupply().call()
print(result)
It is not the only way to perform this operation. You can also use public methods and functions described in the documentation. When you dive deeper into this topic, you’ll learn about creating, deploying, and compiling contracts.
Now we proceed with transactions, the main operation on Python Web3. You can assign them, send messages, and do other operations with your private keys. The easiest way to receive them is to use a Metamask wallet. It provides users with access to their Ether wallet with a simple browser extension. You should export it and use a local private key to assign and send transactions.
There are different ways of sending transactions:
The point of action stays the same in each case: you write some data and then update and check its state. We’ll try some interactions to understand these mechanisms better. For stronger security measures, use a personal blockchain, such as Ganache. It allows you to run tests and check commands and the state of the net without showing your private keys.
You can start with building a dictionary to operate with during a transaction. It can look the following way:
nonce = web3.eth.getTransactionCount(account_1)
tx = {
'nonce': nonce,
'to': account_2,
'value': web3.toWei(1, 'ether'),
'gas': 2000000,
'gasPrice': web3.toWei('50', 'gwei'),
}
Look at a few explanations:
The finishing step is to sign a transaction, and here is the place to use your private keys. They verify the sending, here is why no one except you should know them. After assigning, a transaction must be sent to the network in the following way:
tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
print(web3.toHex(tx_hash))
This action will return the hash of the transaction. Further, you can convert the transaction results into Hex format and print them. This is how Ether can be sent from one account to another via the Web3 py library.
If you are familiar with Python quite well, have a look at Vyper. It is a programming language, quite similar to the Python web3 type, composed especially for smart contracts development.
This is a necessary function while we are building history analysis. The result of this type of function input can look the following way:
There are certain functions allowing you to receive the necessary data:
Let’s use the ‘for’ cycle to build the block history function. Every time we take the latest block and count 10 back. It will look like that:
# get latest block number
print(web3.eth.blockNumber)
# get latest block
print (web3.eth.getBlock('latest'))
# get latest 10 blocks
latest = web3.eth.blockNumber
for i in range(0, 10):
print (web3.eth.getBlock(latest - i))
Another great ability we receive is a transaction checkup via the block number. This is how it goes:
hash = 'YOUR_WALLET_NUMBER'
print(web3.eth.getTransactionByBlock(hash, 2))
We have given an overview of some basic operations with the Web3 Python library. You can get a complete understanding by reading the documentation of this library, their coding guides, and developers’ advice on choosing software. Also, you can move to more complicated operations, such as calling smart contract functions via explaining articles. There are many programs and operations to choose from, giving you great freedom. At the exact moment, you take up the risk of entrusting your data to someone else. However, Python Web3 blockchain technologies minimize the chance of data stealth.
Does it still look difficult, or take too much time to set up? If you want to minimize your work, then apply a Blockchain API. Most problems here are already solved, and the URL is already set into the configuration. You don’t have to set up essential functions every time and deeply understand those algorithms. Take a close look at the RPC Fast solution from Dysnix and continue developing DApps with ease.