Transfer HBAR

Introduction to Transferring HBAR

This tutorial will walk you through a TransferTransaction and show you how to transfer HBAR between accounts, initialize a Hedera client, securely sign and submit a transfer transaction, and verify the transaction was successful using the Hedera Mirror Node.

What you will accomplish

By the end of this tutorial, you will be able to:

  • Create and send a transfer transaction.

  • Send an account balance query.

  • Query the transaction via Mirror Node API.

  • View your transaction on a Mirror Node Explorer.


Prerequisites

Before you begin, you should have completed the following tutorials:


Step 1: Navigate to the transfer example in the project directory

From the root directory of the project, cd (change directories) into the transfer transaction example script.

cd transfer

If you completed a previous example in the series, you can go back to the root directory and cd into this example.

cd ../transfer

If you want to get back to the root directory, you can CD out from any directory with this command

cd ../

You can follow along through the code walkthrough or skip ahead to execute the program here.


Step 2: Guided Code Walkthrough

Open the transfer HBAR script (e.g., /transfer/script-transfer-hbar...) in a code editor like VS Code, IntelliJ, or a Gitpod instance. The imports at the top include modules for interacting with the Hedera network via the SDK. The @hashgraph/sdk enables account management and transactions like creating a token while the dotenv package loads environment variables from the .env file, such as the operator account ID, private key, and name variables.

ScriptTransferHbar.java
package transfer;

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.net.URI;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import com.hedera.hashgraph.sdk.*;

import io.github.cdimascio.dotenv.Dotenv;

public class ScriptTransferHbar {
    public static void main(String[] args) throws Exception {
        System.out.println("🏁 Hello Future World - Transfer HBAR - start");

	    // Load environment variables from .env file
        Dotenv dotenv = Dotenv.configure().directory("../").load();
        String operatorIdStr = dotenv.get("OPERATOR_ACCOUNT_ID");
        String operatorKeyStr = dotenv.get("OPERATOR_ACCOUNT_PRIVATE_KEY");
        if (operatorIdStr == null || operatorKeyStr == null) {
            throw new RuntimeException("Must set OPERATOR_ACCOUNT_ID, OPERATOR_ACCOUNT_PRIVATE_KEY");
        }
        if (operatorKeyStr.startsWith("0x")) {
            operatorKeyStr = operatorKeyStr.substring(2);
        }

	    // Initialize the operator account
        AccountId operatorId = AccountId.fromString(operatorIdStr);
        PrivateKey operatorKey = PrivateKey.fromStringECDSA(operatorKeyStr);
        Client client = Client.forTestnet().setOperator(operatorId, operatorKey);
        System.out.println("Using account: " + operatorIdStr);
}

Create a Hedera Testnet Client

To set up your Hedera Testnet client, create the client and configure the operator using your testnet account ID and private key. The operator account covers transaction and query fees in HBAR, with all transactions requiring a signature from the operator's private key for authorization.

ScriptTransferHbar.java
//Create your Hedera Testnet client
Client client = Client.forTestnet();

//Set your account as the client's operator
client.setOperator(operatorId, operatorKey);

//Set the default maximum transaction fee (in Hbar)
client.setDefaultMaxTransactionFee(new Hbar(100));

//Set the maximum payment for queries (in Hbar)
client.setDefaultMaxQueryPayment(new Hbar(50));

To avoid encountering the INSUFFICIENT_TX_FEE error while executing transactions, you can also specify the maximum transaction fee limit through the .setDefaultMaxTransactionFee() method and the maximum query payment through the .setDefaultMaxQueryPayment() method to control costs, ensuring your client operates within your desired financial limits on the Hedera Testnet.

🚨 How to resolve the INSUFFICIENT_TX_FEE error

To resolve this error, you must adjust the max transaction fee to a higher value suitable for your needs.

Here is a simple example addition to your code:

Copy

const maxTransactionFee = new Hbar(XX); // replace XX with desired fee in Hbar

In this example, you can set maxTransactionFee to any value greater than 5 HBAR (or 500,000,000 tinybars) to avoid the "INSUFFICIENT_TX_FEE" error for transactions greater than 5 HBAR. Please replace XX with the desired value.

To implement this new max transaction fee, you use the setDefaultMaxTransactionFee() method as shown below:

Copy

client.setDefaultMaxTransactionFee(maxTransactionFee);

Create a Transfer Transaction

Create and initialize a transfer transaction (TransaferTransaction) by specifying the sender account, receiver account, and transfer amount. Refer to the transaction and query fees table for the base transaction fee. In the code snippet below, you use the new testnet account you created in the Get Your Testnet Account guide to debit from your operator account (-3 HBAR) and credit accounts 0.0.200(1 HBAR) and 0.0.201 (2 HBAR).

ScriptTransferHbar.java
AccountId recipientAccount1 = AccountId.fromString("0.0.200");
AccountId recipientAccount2 = AccountId.fromString("0.0.201");
TransferTransaction transferTx = new TransferTransaction()
     .setTransactionMemo("Hello Future World transfer - xyz")
     // Debit  3 HBAR from the operator account (sender)
     .addHbarTransfer(operatorId, Hbar.from(-3, HbarUnit.HBAR))
     // Credit 1 HBAR to account 0.0.200 (1st recipient)
     .addHbarTransfer(recipientAccount1, Hbar.from(1, HbarUnit.HBAR))
     // Credit 2 HBAR to account 0.0.201 (2nd recipient)
     .addHbarTransfer(recipientAccount2, Hbar.from(2, HbarUnit.HBAR))
     // Freeze the transaction to prepare for signing
     .freezeWith(client);

// Get the transaction ID for the transfer transaction
TransactionId transferTxId = transferTx.getTransactionId();
System.out.println("The transfer transaction ID: " + transferTxId.toString());

Sign the Transfer Transaction

The transaction must be signed using the private key of the sender's (operator) account. This ensures that the sender authorizes the transfer. Since you are transferring from the account associated with the client, you do not need to sign the transaction explicitly, as the operator account (the account transferring the HBAR) signs all transactions to authorize the transaction fee payment.

ScriptTransferHbar.java
// Sign with the operator key
TransferTransaction transferTxSigned = transferTx.sign(operatorKey);

// Submit the transaction to the Hedera Testnet
TransactionResponse transferTxSubmitted = transferTxSigned.execute(client);

To verify that the transaction has reached consensus on the network, submit a request for the transaction receipt. The request returns the transaction's status to your console. If the console returns a SUCCESS status, the transaction was successfully processed into the consensus state.

script-transfer-hbar.js
// Get the transfer transaction receipt 
const transferTxReceipt = await transferTxSubmitted.getReceipt(client);

// Get the transaction consensus status
const transactionStatus = transferTxReceipt.status;

// Log the transaction status
logger.log('The transfer transaction status is:', transactionStatus.toString(),);

Query the Account Balance

Verify the account balance was updated for the account (0.0.201, 0.0.200) you transferred HBAR to by sending an account balance query. This query will check the current balance of the specified account. The current account balance should be the sum of the initial balance plus the transfer amount. For example, if the initial account balance is 100 HBAR, the balance after transferring 2 HBAR will be 102 HBAR.

ScriptTransferHbar.java
// Query HBAR balance using AccountBalanceQuery
AccountBalance newAccountBalance = new AccountBalanceQuery()
    .setAccountId(operatorId)
    .execute(client);
    
// Get the new HBAR balance
Hbar newHbarBalance = newAccountBalance.hbars;

// Print the new account balance after the transfer
System.out.println(
    "The new account balance after the transfer: " +
    newHbarBalance.toString()
);

Query the Transfer Transaction via Mirror Node API

Mirror nodes store the history of transactions that took place on the network. To query the transaction, use the Mirror Node API with the path /api/v1/transactions/${transferTxIdMirrorNodeFormat}. This API endpoint allows you to retrieve the details of a specified transfer transaction ID.

  • Specify transferTxId within the URL path

  • Specify 0 as the nonce query parameter

The constructed transferTxVerifyMirrorNodeApiUrl string should look like this:

ScriptTransferHbar.java
String transferTxVerifyMirrorNodeApiUrl =
    "https://testnet.mirrornode.hedera.com/api/v1/transactions/" + 
    transferTxIdMirrorNodeFormat;
Learn more about Mirror Node APIs

You can explore the Mirror Node APIs interactively via its Swagger page: Hedera Testnet Mirror Node REST API.

You can perform the same Mirror Node API query as transferTxVerifyMirrorNodeApiUrl above. This is what the relevant part of the Swagger page would look like when doing so:

➡ You can learn more about the Mirror Nodes via its documentation: REST API.


Step 3: Run the Transfer Transaction Script

In the terminal, cd into the ./transfer directory and run the transfer transaction script:

node script-transfer-hbar.js

Sample output:

🏁 Hello Future World - Transfer Hbar - start  
Read .env file
Using account: 0.0.1455

🟣 Creating, signing, and submitting the transfer transaction  
↪️ file:///workspace/hello-future-world-x/transfer/script-transfer-hbar...
The transfer transaction ID: 0.0.1455@1724452532.168163302
The transfer transaction status is: SUCCESS
The new account balance after the transfer: 3655.62282828 

🟣 View the transfer transaction transaction in HashScan  
↪️ file:///workspace/hello-future-world-x/transfer/script-transfer-hbar...
Copy and paste this URL in your browser:
 https://hashscan.io/testnet/transaction/0.0.1455@1724452532.168163302

🟣 Get transfer transaction data from the Hedera Mirror Node  
↪️ file:///workspace/hello-future-world-x/transfer/script-transfer-hbar...
The transfer transaction Hedera Mirror Node API URL:
 https://testnet.mirrornode.hedera.com/api/v1/transactions/0.0.1455-1724452532-168163302?nonce=0
The debit, credit, and transaction fee amounts of the transfer transaction:
┌─────────┬───────────────┬─────────────────┐
 (index) │ Account ID    │ Amount          │
├─────────┼───────────────┼─────────────────┤
 0        '0.0.1455'     '-3.00173036 ℏ' 
 1        '0.0.200'      '1 ℏ'           
 2        '0.0.201'      '2 ℏ'           
└─────────┴───────────────┴─────────────────┘

🎉 Hello Future World - Transfer Hbar - complete  

View the Transfer Transaction and Transaction Fees in HashScan

To view and verify the transaction details, copy, paste, and open the HashScan URL from the console output in your browser.

🟣 View the transfer transaction transaction in HashScan  
↪️ file:///workspace/hello-future-world-x/transfer/script-transfer-hbar...
Copy and paste this URL in your browser:
 https://hashscan.io/testnet/transaction/0.0.1455@1724452532.168163302

The Hedera network Transaction fees are split between two accounts. Most of the fee goes to the fee collection account { 2 } to cover network expenses like processing, bandwidth, and storage costs. The remaining portion is paid to account 0.0.7 { 1 }, the consensus node fee collection account, which plays a critical role in the Hedera network's consensus by validating and processing transactions. This fee structure reflects the actual costs of transactions, protecting against abuse such as Denial of Service (DoS) attacks and ensuring scalable network usage.

  • { 0 } Debit (add 1 - 5 for exact amount) from operator account 0.0.464xxx -3.00173036

  • { 1 } Credit new account 0.0.200 1

  • { 2 } Credit new account 0.0.201 2

  • { 3 } Node fee is paid to account 0.0.4 0.00007032

  • { 4 } Hedera fee collection account 0.0.98 0.00149404

  • { 5 } Staking reward account fee to 0.0.800 0.00016600

    • 0.00007032 + 0.00149404 + 0.00016600 + 10 = 3.00173036

Note: Please see the transaction and query fees table for the base transaction fee.


Code Check ✅


Complete

Congratulations, you have completed the Transfer HBAR tutorial in the Getting Started series for the Web2 Developers learning path! 🎉🎉🎉

You learned how to:


Next Steps

Continue building on Hedera with another tutorial in the series to explore more Hedera services.

Have questions? Join the Hedera Discord and post them in the developer-general channel or ask on Stack Overflow.

Last updated

#2871: HIP-423 long term scheduled transactions

Change request updated