简体   繁体   中英

Decimal error in token balance from wallet in py

I am trying to correctly fetch the value of a token in my Wallet. The token have 18 decimal but the function contract.functions.decimals().call() returns 9 decimal. I've tried many examples but the error is the same. This is my code:

import json
import requests
from web3
import Web3

# Check Tokens Balance
MyAddress = '0xD036680F1d50C11B5924Ac487bf7E58632020a79'
TokenAddress = '0xacFC95585D80Ab62f67A14C566C1b7a49Fe91167'

#
Get ABI from BSCscan
bsc = 'https://bsc-dataseed.binance.org/'
web3 = Web3(Web3.HTTPProvider(bsc))
url_eth = 'https://api.bscscan.com/api'
contract_address = web3.toChecksumAddress(TokenAddress)

API_ENDPOINT = url_eth + '?module=contract&action=getabi&address=' + str(contract_address)
r = requests.get(url = API_ENDPOINT)
response = r.json()
abi = json.loads(response['result'])

# Call contract
contract = web3.eth.contract(address = contract_address, abi = abi)
totalSupply = contract.functions.totalSupply().call()
print(totalSupply)
print(contract.functions.name().call())
print(contract.functions.symbol().call())
print(contract.functions.decimals().call())
address = web3.toChecksumAddress(MyAddress)
balance = contract.functions.balanceOf(address).call()
print(web3.fromWei(balance, 'ether'))

This is the result in console:

100000000000000000000000000
FEGtoken
FEG
9
3.660343728974475686

But in my wallet the balance is 3660343519.636 FEG

I don't understand how to fix this error.

I ran into a similar issue. The reason you're getting this problem is that not every token has the same amount of decimals. MOST coins have 18 decimal points, which equals 'ether', but as you can see, contract.functions.decimals().call() returned 9. That means that when you print out web3.fromwWei, you need to call 'wei'. To make it more dynamic, pass in the value you get from the decimals().call() method.

Question though: contract.functions.decimals().call() takes roughly 1.4 seconds for me. In comparison, calling web3.eth.contract(address = contract_address, abi = abi) takes 0.01 seconds. Is this some sort of API bug? And are there any alternatives for returning decimals value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM