James Bachini

How To Check Token Balances Using Python

web3 python

To check a wallet token balance on the Ethereum blockchain using Python you will need the following:

  • Infura API Key You can get this by signing up at Infura.
  • Python Installed on your device, download here.
  • Web3.py This is a Python library for interacting with the Ethereum blockchain.

Once we have our API key ready and Python installed we can install web3.py using the following command

pip install web3

Now let’s create a file called balance.py and add the following code. Note the code is also available in the Github repository: https://github.com/jamesbachini/Web3-Python-Scripts

from web3 import Web3

infura_url = 'https://mainnet.infura.io/v3/YOUR_API_KEY_HERE'
web3 = Web3(Web3.HTTPProvider(infura_url))

wallet_address = '0x123e710c69b6806ef32Cf52e49dCC5EEEc368a22'
token_contract_address = '0x7eae7422f633429EE72BA991Ac293197B80D5976'

token_abi = [
    {
        "constant": True,
        "inputs": [{"name": "owner", "type": "address"}],
        "name": "balanceOf",
        "outputs": [{"name": "balance", "type": "uint256"}],
        "type": "function"
    },
    {
        "constant": True,
        "inputs": [],
        "name": "decimals",
        "outputs": [{"name": "", "type": "uint8"}],
        "type": "function"
    }
]

token_contract = web3.eth.contract(address=token_contract_address, abi=token_abi)
balance = token_contract.functions.balanceOf(wallet_address).call()
decimals = token_contract.functions.decimals().call()
adjusted_balance = balance / (10 ** decimals)
print(f"Token Balance: {adjusted_balance}")

Enter your API into the URL on line 3 and then let’s run the script with:

python ./balance.py
Check token balance with Python and web3

This script will connect to the Ethereum blockchain via Infura, interact with the specified token contract, and print the token balance of the specified wallet address.


Get The Blockchain Sector Newsletter, binge the YouTube channel and connect with me on Twitter

The Blockchain Sector newsletter goes out a few times a month when there is breaking news or interesting developments to discuss. All the content I produce is free, if you’d like to help please share this content on social media.

Thank you.

James Bachini

Disclaimer: Not a financial advisor, not financial advice. The content I create is to document my journey and for educational and entertainment purposes only. It is not under any circumstances investment advice. I am not an investment or trading professional and am learning myself while still making plenty of mistakes along the way. Any code published is experimental and not production ready to be used for financial transactions. Do your own research and do not play with funds you do not want to lose.