Search code examples
pythonbinance-smart-chain

Query account balance on Binance Smart Chain - decoding bech32 failed


I am trying to get the balance of a public address via Binance Chain API

account_id = "0x1f5ff990d661a4DFDC0Ff7D63Ae6A7E995475b95"
response = requests.get("https://dex.binance.org/api/v1/account/" + account_id.lower())
account = response.json()

But I get the following error

{'code': 400, 'message': 'decoding bech32 failed: failed converting data to bytes: invalid character not part of charset: 98'}

How do I convert a public address into bech32 format? Or is there a better way to extract the balance of an address?


Solution

  • Eventually figured out that its not you. Its the binance API giving you that error. After doing some digging I found that for some reason the binance API only takes Bech32 format addresses with the tag of bnb:

    import requests 
    account_id = "bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m" # address 91937520f40458f5b414d267961b46c19789dd70
    
    response = requests.get("https://dex.binance.org/api/v1/account/" + account_id.lower())
    account = response.json()
    print(account)
    

    But when you search/get an address it gives it to you in normal 0x format

    I did find a converter online that was able to decode the sample address to normal: https://slowli.github.io/bech32-buffer/

    enter image description here

    but for some reason the API still reports 404 for your address with the same converter:

    import requests 
    account_id = "bnb1ra0lnyxkvxjdlhq07ltr4e48ax25wku4nhunzs" # address 1f5ff990d661a4DFDC0Ff7D63Ae6A7E995475b95
    
    response = requests.get("https://dex.binance.org/api/v1/account/" + account_id.lower())
    account = response.json()
    print(account)
    

    enter image description here

    Even though if you use the exact same address you can see it using the smart chain explorer. https://bscscan.com/address/0x1f5ff990d661a4DFDC0Ff7D63Ae6A7E995475b95

    Anyways. The answer to this question is that you are providing the address to the API without converting it to Bech32 format first. Now you just need to figure out why it still returns 404 even with the address converted to bech32. Might be something to raise with the binance team themselves