8

Hi i just recently started working with Nami Wallet to be implementes in a web app, but when im trying to get my wallet balance:

window.cardano.getBalance().then(res => console.log(res))

its returning an string.

"1a3b983883"

would love to know what that is and if i can convert that to an actual number.

Picture:

getBalance() response

2 Answers 2

7

getBalance function returns cbor encoded hex string, so you should actually decode it.

Easiest way to do it is by using Cardano Serialization Lib.

After you've downloaded the library you can decoded it by doing this:

import * as wasm from '@emurgo/cardano-serialization-lib-browser';

window.cardano.getBalance().then(res => {
   const balance = wasm.Value.from_bytes(Buffer.from(res, 'hex'));
   const lovelaces = balance.coin().to_str();

   console.log(lovelaces);
})

EDIT:

Thanks to Hernan Rajchert for explaining on how to get lovelaces from Values object.

8
  • 2
    thanks! but this code returns this object "{ptr: 1180552}", what to do with that? Commented Oct 13, 2021 at 15:43
  • 1
    Yeah I got the same response so I'm not too sure about it. I'd recommend you rather building your transactions using TransactionBuilder, because it offers you nice way to specify change address and etc.
    – pyropy
    Commented Oct 14, 2021 at 9:50
  • 2
    @DanielDiaz, that is a pointer to the WASM object, if you need to get the lovelace value as string you can do balance.coin().to_str() Commented Nov 3, 2021 at 20:30
  • 1
    Yes as DanielDias suggested thats the way to go I got my balance in lovelaces Commented Nov 6, 2021 at 13:40
  • 1
    Why do I get "Uncaught ReferenceError: Buffer is not defined"? Commented Dec 10, 2021 at 16:50
-1

You have to use the cbor npm package to extract the balance value:

import cbor from 'cbor';

const getAdaBalance = (string) => {
  const decoded = cbor.decode(string)
  return ((typeof decoded === 'number') ? decoded : decoded[0]) / 1_000_000;
}

let myBalance = getAdaBalance(await window.cardano.getBalance());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.