簡體   English   中英

如何使用 web3.py 在給定的 ETH 地址獲取特定的代幣余額

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

我開始使用 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'

您必須查看合約是否具有“balance_of”功能。 執行時

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

您正在執行合約的 balance_of 功能,如果合約沒有該功能,則會出現錯誤

在最后一個代碼示例中,嘗試將第二行修改為: balance = instance.functions.balanceOf().call({'from':send_address}) 平衡后的括號是您要傳遞給solidity函數的參數。

這在今天肯定有效:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM