Search code examples
python-3.xweb3py

How to call a contract's balanceOf function for a specific block using Web3.py


How can I get the balance of a token at a specific time? I'm using Web3.py. Nothing I seem to try works. I can get the latest balance of USDC for a particular wallet like this:

contract = web3.eth.contract('0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', abi=self.ABI)

raw_balance = contract.functions.balanceOf('0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B').call()

I try to specify the block number inside of the call() function:

raw_balance = contract.functions.balanceOf(wallet_address).call(block_identifier=13372637)

But I get an error each time:

requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://mainnet.infura.io/v3/...


Solution

  • Try doing

    contract.functions.<function>.call(block_identifier=web3.eth.get_block('latest')['number']) 
    

    If that works using the latest block, then you might need to pay extra to get historical data, unfortunately...

    EDIT: Another possibility is you're using np.int64 or another int variant. Try enforcing int(block_no) and see if that works

    EDIT EDIT: Also, try using https://docs.alchemy.com/alchemy/ instead of Infura. Free account worked for me..