Search code examples
nearprotocol

How to get certain acount's balance using Nearlib.js


Let's say we initialize near like so and that the user is already logged in:

    const near = await window.nearlib.connect(Object.assign({ deps: { keyStore: new window.nearlib.keyStores.BrowserLocalStorageKeyStore() } }, window.nearConfig));
    const walletAccount = new window.nearlib.WalletAccount(near);

I want to be able to get an account's NEAR balance using something like:

near.getBalanceOf(walletAccount.getAccountId()).then(...)

or maybe

walletAccount.getBalance().then(...)

Solution

  • WalletAccount is just used to login with the wallet. All the relevant API is located in Account class. Here is a way to query your own account info:

    let account = await near.account(walletAccount.getAccountId());
    console.log(await account.state());
    

    The result will be something like this:

    {
      "amount":"20999000097842111450",
      "code_hash":"11111111111111111111111111111111",
      "staked":"2000000000",
      "storage_paid_at":324708,
      "storage_usage":551
    }