Paras
Paras

Reputation: 3481

How to get the specific token balance available at a give ETH address using web3.py

I am getting started with web.py. I have a requirement where I need to get the available token balance at a given ETH address(this address is not the contract owner), going through the docs I stumble upon the following functiion :

https://web3py.readthedocs.io/en/stable/contracts.html#web3.contract.ContractFunction.call

token_contract.functions.myBalance().call({'from': web3.eth.accounts[1]})

so on the above lines, I wrote this :

from web3 import HTTPProvider, Web3
import requests

w3 = Web3(HTTPProvider('https://ropsten.infura.io/RPw9nHRS7Ue47RaKVvHM'))

url_eth = "https://api.etherscan.io/api"
contract_address = '0x0CdCdA4E7FCDD461Ba82B61cBc4163E1022f22e4'
API_ENDPOINT = url_eth+"?module=contract&action=getabi&address="+str(contract_address)

r = requests.get(url = API_ENDPOINT)
response = r.json()

instance = w3.eth.contract(
    address=Web3.toChecksumAddress(contract_address),
    abi = response["result"]
)
send_address = "0xF35A192475527f80EfcfeE5040C8B5BBB596F69A"
balance = instance.functions.balance_of.call({'from':send_address}) 
#balnce = instance.functions.myBalance.call({'from':send_address})
print("----------------------",balance)

I get the following error :

"Are you sure you provided the correct contract abi?"
web3.exceptions.MismatchedABI: ("The function 'balance_of' was not foundin this contract's abi. ", 'Are you sure you provided the correct contract abi?')

**Update ** I got rid of the above exception, now I'm getting the following exception :

send_address = "0xF35A192475527f80EfcfeE5040C8B5BBB596F69A"
balance = instance.functions.balanceOf.call(send_address)
#Error :
call_transaction = dict(**transaction)
TypeError: type object argument after ** must be a mapping, not str

If I try this :

send_address = "0xF35A192475527f80EfcfeE5040C8B5BBB596F69A"
balance = instance.functions.balanceOf.call({'from':send_address})
#Error:
AttributeError: 'balanceOf' object has no attribute 'args'

Upvotes: 3

Views: 10489

Answers (3)

elier
elier

Reputation: 459

This works for sure as of today:

send_address = "0xF35A192475527f80EfcfeE5040C8B5BBB596F69A"
balance = instance.functions.balanceOf(send_address).call()

Upvotes: 1

Alvaro G
Alvaro G

Reputation: 61

you have to see if the contract has the function "balance_of". At the time of executing

balance = instance.functions.balanceOf.call(send_address)

You are executing the balance_of function of the contract, if the contract does not have that function it gives the error

Upvotes: 1

nikos fotiadis
nikos fotiadis

Reputation: 1085

In the last code sample try to modify the second line to look like this: balance = instance.functions.balanceOf().call({'from':send_address}). The parenthesis after balance of are the arguments you are passing to the solidity function.

Upvotes: 2

Related Questions