In this article we will get the balance from a wallet using the web3 library. If you just want to the code, here it is:
from web3 import Web3 # rpc urls are endpoints used to send and receive data to a specific blockchain # here we're interacting with Polygon's testnet, the mumbai testnet mumbai_rpc_url = "https://rpc-mumbai.maticvigil.com" # The provider is your connection to a blockchain web3 = Web3(Web3.HTTPProvider(mumbai_rpc_url)) #log if we're connected or not print(web3.isConnected()) #get the blocknumber print(web3.eth.blockNumber) #get the balance #balance is shown in Wei, which is a huge number. Wei is likes 'pennies' in the ethereum world wallet_address = "0x55c9bBb71a5CC11c2f0c40362Bb691b33a78B764" print(web3.eth.getBalance(wallet_address)) #balance here is formatted in ether, balance = web3.eth.getBalance(wallet_address) print(web3.fromWei(balance,"ether"))
Let's get into it
We'll setup our environment first and then dive into the code.
Setting up our environment
The first thing that we need to do is create a virtual environment and install the web3 library.
Type the following command to create a virtual environment and to activate it.
python3 -m env ./myv source ./myv/bin/activate
Next we need to pip install the web3 library.
pip install web3
Once you're done, create a
.py file and open your code editor.
Time to code
First we import the web3 library.
from web3 import Web3
Next we need to connect to a blockchain. We need to pass a
RPC url for that. I'm going to connect to the
Mumbai network, which is the test network of
mumbai_rpc_url = "https://rpc-mumbai.maticvigil.com" web3 = Web3(Web3.HTTPProvider(mumbai_rpc_url))
With the web3 library we can check whether we're connected
Now to get the balance we call the method
getBalance, but first we need to tell our program which wallet we want to target.
wallet_address = "0x55c9bBb71a5CC11c2f0c40362Bb691b33a78B764" print(web3.eth.getBalance(wallet_address))
The balance is returned in
Wei, which is a super long number. Wei to ether is like pennies to dollar. The only difference is a 100 pennies equal 1 dollar and a 1,000,000,000,000,000,000 wei (10^18) equals 1 ether.
So let's format the balance to a more readable format.
balance = web3.eth.getBalance(wallet_address) print(web3.fromWei(balance,"ether"))
With a couple of lines of code you've used Python to interact with a blockchain. If you're looking for more code snippets like this, check out my Github repo or stay tuned for more articles in this series.