trying to call balanceOf function in ethereum using web3.py library but getting error
Asked Answered
P

1

8
import json
from web3 import Web3
infura_url = "https://mainnet.infura.io/v3/5b314a9b373442fc8ed0c9cd184e838f"
web3 = Web3(Web3.HTTPProvider(infura_url))
abi=json.loads('[{"constant":true,"inputs":..........] large array')
address = "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07"
contract = web3.eth.contract(address=address, abi=abi)
totalSupply = contract.functions.totalSupply().call()
print(totalSupply)
print(contract.functions.name().call())
print(contract.functions.symbol().call())
balance = contract.functions.balanceOf('0x2551d2357c8da54b7d330917e0e769d33f1f5b93').call()
print(web3.fromWei(balance, 'ether'))

But when I run this code I get this error

web3.exceptions.InvalidAddress: ('Web3.py only accepts checksum addresses. The software that gave you this non-checksum address should be considered unsafe, please file it as a bug on their platform. Try using an ENS name instead. Or, if you must accept lower safety, use Web3.toChecksumAddress(lower_case_address).', '0x2551d2357c8da54b7d330917e0e769d33f1f5b93')--> error at this line

Perrotta answered 3/8, 2019 at 6:28 Comment(7)
What is the line who gives an error ?Jovian
balance=contract.functions.balanceOf('0x2551d2357c8da54b7d330917e0e769d33f1f5b93').call()Perrotta
Are you sure ? At this page: github.com/ethereum/web3.py/issues/740 looks like to be contract=web3.eth.contract(address=address,abi=abi)Jovian
there is no error as other functions are workingPerrotta
feromWei function ? i don't see this function on documentation ?Jovian
OK, i see this function works on outdate versions... an possible error i see, its print(web3.feromWei(balance,ether)) ether need be 'ether'Jovian
Please add your web3 version here.Jovian
J
13

Possible solution:

You don't show your Web3 version, at this time fromWei function its outdated and removed from documentation.

contract.functions.balanceOf('0x2551d2357c8da54b7d330917e0e769d33f1f5b93').call()

You got error in above function, because the address you insert isn't a checksum address. If you don't understand what is checksum address, here you have a great explanation, what to do in this case? Obviously you need convert the address you inserted on contract.functions.balanceOf to checksum address.

address2 = Web3.toChecksumAddress('0x2551d2357c8da54b7d330917e0e769d33f1f5b93')
balance=contract.functions.balanceOf(address2).call()

#Don't use fromWei function if its not defined on your Web3 documentation
Jovian answered 3/8, 2019 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.