如何使用web3.py在给定的ETH地址获得特定的代币余额

时间:2019-02-05 05:11:07

标签: python python-3.x web3 web3js

我正在开始使用web.py。我有一个需求,我需要在给定的ETH地址(该地址不是合同所有者)上获取可用的代币余额,通过文档我偶然发现以下功能:

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

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

所以在上述几行中,我这样写:

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)

我收到以下错误:

"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?')

**更新**我摆脱了上面的异常,现在我得到了以下异常:

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

如果我尝试这样做:

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

3 个答案:

答案 0 :(得分:1)

你要看看合约有没有“balance_of”这个功能。执行时

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

您正在执行合约的 balance_of 函数,如果合约没有该函数则会报错

答案 1 :(得分:0)

在最后一个代码示例中,尝试将第二行修改为:balance = instance.functions.balanceOf().call({'from':send_address})。平衡后的括号是您要传递给Solidity函数的参数。

答案 2 :(得分:0)

这在今天肯定有效:

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