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
transfer
example in the project directoryFrom 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.
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.
//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.
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).
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.
// 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.
// 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.
// 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 pathSpecify
0
as thenonce
query parameter
The constructed transferTxVerifyMirrorNodeApiUrl
string should look like this:
String transferTxVerifyMirrorNodeApiUrl =
"https://testnet.mirrornode.hedera.com/api/v1/transactions/" +
transferTxIdMirrorNodeFormat;
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: [email protected]
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/[email protected]
π£ 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/[email protected]
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
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 Consensus Node services.
Create a Topic
Learn how to create topics and publish messages using the Hedera Consensus Service (HCS).
Last updated
Was this helpful?