1

I'm using an API to get balance in a bitcoin address.

My code is:

async function getWalletBalance(address) {
    try {
        const response = await got(`blockchain.info/balance?active=${address}`)
        return response.body.address.final_balance
    } catch(err) {
        return err
    }
}

The returning JSON is:

{
  "3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r": {
    "final_balance": 15392048444281,
    "n_tx": 3938,
    "total_received": 138450271881712
  }
}

But when I try to read the final balance, it gives me undefined. How do I fix this?

Jack
  • 43
  • 11

1 Answers1

2

response.body.address.final_balance is looking for the literal key address, not looking for the key 3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r in your example.

Using response.body[address].final_balance instead should fix your problem.

The snippet below is slightly modified (and doesn't have a call to get a real response) but should do the job.

function getWalletBalance(address) {
    try {
        const body = {
          "3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r": {
            "final_balance": 15392048444281,
            "n_tx": 3938,
            "total_received": 138450271881712
          }
        };
        console.log('using body[address]:', body[address].final_balance);
    } catch(err) {
        return err
    }
}

getWalletBalance("3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r");
elsyr
  • 736
  • 3
  • 9
  • Still returning `undefined`. – Jack Dec 23 '17 at 13:50
  • Added a snippet that you can run and look at. – elsyr Dec 23 '17 at 21:49
  • Still not working. I don't understand what I've done wrong. – Jack Dec 24 '17 at 00:12
  • At what part of your access does it return undefined? It should be pretty easy to figure out what your object looks like with a debugger (or just console logging if you're not familiar). Are you sure response isn't undefined? If it's there, can you access response.body? If yes, try response.body[address], and so on until you find exactly where the problem is. – elsyr Dec 24 '17 at 01:55
  • console logging response.body works fine, but as soon as I try to access [address], it immediately returns undefined. I even tried hard coding the address and it still didn't work. – Jack Dec 24 '17 at 02:59
  • response.body returns exactly the JSON you posted in your original question? When using response.body[address], are you sure address refers to a string? Same question for when you hardcoded it. – elsyr Dec 24 '17 at 03:01