Get Other Account Info

In this section you will learn how to queries the account balance of another account on the Hedera network using the provided account credentials and the Hedera JavaScript SDK.

Prerequisites

  • Completed the Introduction step.

  • Completed the Environment Setup step.

  • Completed the Created an Account step.

Step 1 : Imports

  • The code imports necessary modules from the Hedera JavaScript SDK (@hashgraph/sdk): Client, AccountBalanceQuery, and PrivateKey.

  • It also imports the dotenv module to load environment variables from a .env file located in the Account directory.

const {
    Client,
    AccountBalanceQuery,
    PrivateKey 
} = require("@hashgraph/sdk");
require('dotenv').config({ path: 'Account/.env' });

Step 2 : Environment Variables Retrieval

These lines retrieve environment variables such as MY_ACCOUNT_ID, MY_PRIVATE_KEY, and OTHER_ACCOUNT_ID from the .env file using process.env.

const myAccountId = process.env.MY_ACCOUNT_ID;
const myPrivateKey = PrivateKey.fromString(process.env.MY_PRIVATE_KEY);
const otherAccountId = process.env.OTHER_ACCOUNT_ID;

Step 3 : Main Function

  • It creates a client instance for the Hedera testnet.

  • It sets the operator account for the client using the user's account ID and private key.

  • It creates an AccountBalanceQuery object and sets the account ID for which the balance needs to be queried to otherAccountId.

  • It executes the query using the client.

  • If the query is successful, it logs the account balance and information of the other account to the console.

  • Finally, it exits the process.

async function main() {
    const client = Client.forTestnet(); // Create a client for the Hedera testnet

    client.setOperator(myAccountId, myPrivateKey); // Set the operator account for the client

    const query = new AccountBalanceQuery() // Create an account balance query object
     .setAccountId(otherAccountId); // Set the account ID for which the balance needs to be queried

    const accountBalance = await query.execute(client); // Execute the query

    if (accountBalance) { // If the query is successful
        console.log(`The account balance for someone else's account ${otherAccountId} is ${accountBalance.hbars} HBar`);
        console.log("All account Info for the other account:");
        console.log(JSON.stringify(accountBalance)); // Log the account balance and information to the console
    }
    
    process.exit(); // Exit the process
}

Step 4: Execution

This line calls the main() function to start the execution of the script.

main();

Last updated