Get My Account Info

This script queries the account balance of a specified account on the Hedera network using the Hedera JavaScript SDK.

Prerequisites

  • Completed the Introduction step.

  • Completed the Environment Setup step.

Step 1 : Imports and Environment Setup

  • This section imports necessary modules from the Hedera JavaScript SDK (Client, AccountBalanceQuery, 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 the account ID and private key from environment variables defined in the .env file.

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

Step 3 : Main Function

  • It creates a client instance for the Hedera testnet.

  • It sets the operator account for the client using the account ID and private key retrieved from the environment variables.

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

  • It executes the query using the client.

  • If the query is successful, it logs the account balance and all account information (as a JSON string) to the console.

  • Finally, it exits the process.

async function main() {
    // Create our connection to the Hedera network
    const client = Client.forTestnet();

    client.setOperator(myAccountId, myPrivateKey);

    // Create the query
    const query = new AccountBalanceQuery()
     .setAccountId(myAccountId);

    // Sign with the client operator account private key and submit to a Hedera network
    const accountBalance = await query.execute(client);

    if (accountBalance) {
        console.log(`The account balance for account ${myAccountId} is ${accountBalance.hbars} HBar`);

        console.log("All account Info:")
        console.log(JSON.stringify(accountBalance));
    }

    process.exit();
}

Step 4 : Execute

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

main();

Step 5 : To execute the code

To execute the script:

  • Make sure you have Node.js installed on your system.

  • Install the required dependencies by running npm install @hashgraph/sdk dotenv in your terminal.

  • Create a .env file in the Account directory and define MY_ACCOUNT_ID and MY_PRIVATE_KEY variables with your actual Hedera account ID and private key.

  • Run the script by executing node script.js in your terminal, where script.js is the filename of your script.

Last updated