7

I am trying to get the balance in my wallet of specific tokens with no luck. I have found examples online on how to do this task using web3.js, but the methods used seem to be different. I also found this helpful example: How to view custom token balance in ether wallet using web3, however it doesn't seem to be working for me.

Is anyone able to provide a short script that can do this?

As an example, on the polygon network I expect the wallet address 0x0598acaf4eA05D41844b23423ff4E2d9Cf2b481E to contain 0.882 USDT. Is there anyway to get this programmatically?

michael
  • 73
  • 1
  • 1
  • 5

2 Answers2

9

You need the token's ABI and utilize the function balanceOf. Example snippet below:

token = w3.eth.contract(address={token address}, abi={token abi}) # declaring the token contract
token_balance = token.functions.balanceOf({your address}).call() # returns int with balance, without decimals

You can find the token ABI from the block explorer, from the code tab of your token. In your case, here you can find the ABI for USDT's contract. You will need to parse JSON before being able to use it in Python.

bru53001
  • 721
  • 4
  • 9
1

You need the contract's ABI, but any ERC20 standard ABI will do.

def get_balance(user_address):
       contract_address = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
       infura_url = 'https://polygon-mainnet.infura.io/v3/<infura api key>'
       web3 = Web3(Web3.HTTPProvider(infura_url))
       contract = 
       web3.eth.contract(address=Web3.toChecksumAddress(contract_address.lower()), abi=abi)
       balance = contract.functions.balanceOf(Web3.toChecksumAddress(user_address.lower())).call()
       return balance