【问题标题】:How to get the specific token balance available at a give ETH address using web3.py如何使用 web3.py 在给定的 ETH 地址获取特定的代币余额
【发布时间】:2019-06-28 21:26:53
【问题描述】:

我开始使用 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?')

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

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'

【问题讨论】:

    标签: python python-3.x web3 web3js


    【解决方案1】:

    在最后一个代码示例中,尝试将第二行修改为如下所示:balance = instance.functions.balanceOf().call({'from':send_address})。 balance of 之后的括号是你传递给solidity函数的参数。

    【讨论】:

      【解决方案2】:

      您必须查看合约是否具有“balance_of”功能。执行时

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

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

      【讨论】:

        【解决方案3】:

        从今天开始,这肯定有效:

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

        【讨论】:

          猜你喜欢
          • 2022-12-23
          • 2020-10-05
          • 2021-07-28
          • 2018-05-04
          • 2022-11-15
          • 2018-08-08
          • 1970-01-01
          • 1970-01-01
          • 2022-09-26
          相关资源
          最近更新 更多