本文用EOS举例,此EOS为ERC20代币,非EOS主网
infura账户创建方法参考上一篇文章《Python3 使用Web3.py查询以太坊账户余额》
直接上代码,备有注册。直接拷贝即可使用!
from web3 import Web3
def QuerryBalanceEOS(accounts):
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/{此处设置自己托管账户ID}'))
#EOS在ETH上的ERC20合约地址
eos_contract_address = "0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0"
#以下两个函数为检测地址正确性的函数,与实际查询业务无关
a = w3.isAddress(eos_contract_address)
b = w3.isChecksumAddress(eos_contract_address)
#EOS合约代码(部分),因为这里只想做EOS代币的查询函数(balanceOf)
contract_source_code='''
[{
"type":"function",
"name":"balanceOf",
"constant":true,
"payable":false,
"inputs":[{"name":"","type":"address"}],
"outputs":[{"name":"","type":"uint256","value":"0"}]
}]
'''
#很关键,此处一定要转换成基于JSON串的source_code。此处是坑,很多python文章讲解都没有注意此处的转换
abi = json.loads(contract_source_code)
source_code = w3.eth.getCode(eos_contract_address)
#print(source_code)
contract = w3.eth.contract(abi=abi, address=eos_contract_address, bytecode=source_code)
balance = contract.functions.balanceOf(accounts).call()
#balance = w3.eth.getBalance(accounts,'latest')#latest表示使用区块链中最后一个块的状态,也就是最后的余额
print('balance@latest => {0}'.format(balance))
return balance