Transfer HBAR

In this section, you will learn how to transfer HBAR from your account to another on the Hedera test network.

Prerequisites

  • Completed the Introduction step.

  • Completed the Environment Setup step.

  • Completed the Created an Account step.

Step 1 : Imports

  • The script imports necessary modules from the Hedera JavaScript SDK: Client, AccountBalanceQuery, TransferTransaction, Hbar, and PrivateKey.

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

const {
    Client,
    AccountBalanceQuery,
    TransferTransaction,
    Hbar,
    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.

Step 3 : Main Function

  • It creates a client instance for the Hedera testnet and sets the operator account using the user's account ID and private key.

  • It creates a TransferTransaction object to transfer HBars between accounts.

  • The transaction subtracts 10 HBars from the operator account (myAccountId) and adds 10 HBars to the other account (otherAccountId).

  • The transaction is executed, and the resulting transaction ID (txId) is obtained.

  • The receipt of the transaction is retrieved, and the transaction consensus status is obtained from the receipt.

  • Queries are created to retrieve the account balances of both the operator account and the other account.

  • The queries are executed, and the account balances are logged to the console.

Step 4: Execution

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

Last updated

Was this helpful?