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.
import {
Client,
PrivateKey,
AccountId,
TransferTransaction,
Hbar,
HbarUnit,
AccountBalanceQuery,
} from '@hashgraph/sdk';
import dotenv from 'dotenv';
import {
convertTransactionIdForMirrorNodeApi,
createLogger,
} from '../util/util.js';
const logger = await createLogger({
scriptId: 'transferHbar',
scriptCategory: 'task',
});
let client;
async function scriptTransferHbar() {
logger.logStart('Hello Future World - Transfer Hbar - start');
// Read in environment variables from `.env` file in parent directory
dotenv.config({ path: '../.env' });
logger.log('Read .env file');
// Initialise the operator account
const operatorIdStr = process.env.OPERATOR_ACCOUNT_ID;
const operatorKeyStr = process.env.OPERATOR_ACCOUNT_PRIVATE_KEY;
if (!operatorIdStr || !operatorKeyStr) {
throw new Error('Must set YOUR_NAME, OPERATOR_ACCOUNT_ID, OPERATOR_ACCOUNT_PRIVATE_KEY');
}
const operatorId = AccountId.fromString(operatorIdStr);
const operatorKey = PrivateKey.fromStringECDSA(operatorKeyStr);
logger.log('Using account:', operatorIdStr);
}
script-transfer-hbar.go
package main
import (
"encoding/json"
"fmt"
"log"
"math"
"os"
"sort"
"strings"
"time"
"github.com/hashgraph/hedera-sdk-go/v2"
"github.com/imroc/req/v3"
"github.com/joho/godotenv"
)
type TransferMNAPIResponse struct {
Account string `json:"account"`
Amount int64 `json:"amount"`
}
type TransferTransactionMNAPIResponse struct {
Transactions []struct {
Transfers []TransferMNAPIResponse `json:"transfers"`
} `json:"transactions"`
}
func main() {
fmt.Println("🏁 Hello Future World - Transfer Hbar - start")
// Load environment variables from .env file
err := godotenv.Load("../.env")
if err != nil {
log.Fatal("Error loading .env file")
}
// Initialize the operator account
operatorIdStr := os.Getenv("OPERATOR_ACCOUNT_ID")
operatorKeyStr := os.Getenv("OPERATOR_ACCOUNT_PRIVATE_KEY")
if operatorIdStr == "" || operatorKeyStr == "" {
log.Fatal("Must set OPERATOR_ACCOUNT_ID, OPERATOR_ACCOUNT_PRIVATE_KEY")
}
operatorId, _ := hedera.AccountIDFromString(operatorIdStr)
// Necessary because Go SDK v2.37.0 does not handle the `0x` prefix automatically
// Ref: https://github.com/hashgraph/hedera-sdk-go/issues/1057
operatorKeyStr = strings.TrimPrefix(operatorKeyStr, "0x")
operatorKey, _ := hedera.PrivateKeyFromStringECDSA(operatorKeyStr)
fmt.Printf("Using account: %s\n", operatorId)
fmt.Printf("Using operatorKey: %s\n", operatorKeyStr)
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));
script-transfer-hbar.js
// The client operator ID and key is the account that will be automatically set to pay for the transaction fees for each transaction
client = Client.forTestnet().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));
//Create your testnet client
client := hedera.ClientForTestnet()
client.SetOperator(myAccountId, myPrivateKey)
// Set default max transaction fee
client.SetDefaultMaxTransactionFee(hedera.HbarFrom(100, hedera.HbarUnits.Hbar))
// Set max query payment
client.SetDefaultMaxQueryPayment(hedera.HbarFrom(50, hedera.HbarUnits.Hbar))
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:
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());
script-transfer-hbar.js
// Create the transfer transaction
const transferTx = await new TransferTransaction()
.setTransactionMemo(`Hello Future World transfer - ${logger.version}`)
// Debit 3 HBAR from the operator account (sender)
.addHbarTransfer(operatorId, new Hbar(-3, HbarUnit.Hbar))
// Credit 1 HBAR to account 0.0.200 (1st recipient)
.addHbarTransfer('0.0.200', new Hbar(1, HbarUnit.Hbar))
// Credit 2 HBAR to account 0.0.201 (2nd recipient)
.addHbarTransfer('0.0.201', new Hbar(2, HbarUnit.Hbar))
// Freeze the transaction to prepare for signing
.freezeWith(client);
// Get the transaction ID for the transfer transaction
const transferTxId = transferTx.transactionId;
logger.log('The transfer transaction ID:', transferTxId.toString());
script-transfer-hbar.go
recipientAccount1, _ := hedera.AccountIDFromString("0.0.200")
recipientAccount2, _ := hedera.AccountIDFromString("0.0.201")
transferTx, _ := hedera.NewTransferTransaction().
SetTransactionMemo(fmt.Sprintf("Hello Future World transfer - xyz")).
// Debit 3 HBAR from the operator account (sender)
AddHbarTransfer(operatorId, hedera.HbarFrom(-3, hedera.HbarUnits.Hbar)).
// Credit 1 HBAR to account 0.0.200 (1st recipient)
AddHbarTransfer(recipientAccount1, hedera.HbarFrom(1, hedera.HbarUnits.Hbar)).
// Credit 2 HBAR to account 0.0.201 (2nd recipient)
AddHbarTransfer(recipientAccount2, hedera.HbarFrom(2, hedera.HbarUnits.Hbar)).
// Freeze the transaction to prepare for signing
FreezeWith(client)
// Get the transaction ID for the transfer transaction
transferTxId := transferTx.GetTransactionID()
fmt.Printf("The transfer transaction ID: %s\n", transferTxId.String())
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);
script-transfer-hbar.js
// Sign with the operator key
const transferTxSigned = await transferTx.sign(operatorKey);
// Submit the transfer transaction to the Hedera network
const transferTxSubmitted = await transferTxSigned.execute(client);
script-transfer-hbar.go
// Sign with the operator key
transferTxSigned := transferTx.Sign(operatorKey)
// Submit the transaction to the Hedera Testnet
transferTxSubmitted, err := transferTxSigned.Execute(client)
if err != nil {log.Fatalf("Error executing TransferTransaction: %v\n", err)}
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(),);
ScriptTransferHbar.java
// Get the transfer transaction receipt
TransactionReceipt transferTxReceipt = transferTxSubmitted.getReceipt(client);
// Get the transaction consensus status
Status transactionStatus = transferTxReceipt.status;
// Print the transaction status
System.out.println(
"The transfer transaction status is: " + transactionStatus.toString()
);
script-transfer-hbar.go
// Get the transfer transaction receipt
transferTxReceipt, err := transferTxSubmitted.GetReceipt(client)
if err != nil {
log.Fatalf("Error getting receipt for TransferTransaction: %v\n", err)
}
// Get the transaction consensus status
transactionStatus := transferTxReceipt.Status
// Print the transaction status
fmt.Printf("The transfer transaction status is: %s\n", transactionStatus.String())
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()
);
script-transfer-hbar.js
// Query HBAR balance using AccountBalanceQuery
const newAccountBalance = new AccountBalanceQuery()
.setAccountId('0.0.201')
.execute(client);
// Wait for the query result and get the HBAR balance
const newHbarBalance = (await newAccountBalance).hbars;
// Log the new account balance after the transfer
logger.log(
'The new account balance after the transfer:', newHbarBalance.toString()
);
script-transfer-hbar.go
// Query HBAR balance using
newAccountBalance, _ := hedera.NewAccountBalanceQuery().
SetAccountID(operatorId).
Execute(client)
// Get the new HBAR balance
newHbarBalance := newAccountBalance.Hbars
// Print the new account balance after the transfer
fmt.Printf("The new account balance after the transfer: %s\n",
newHbarBalance.String())
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:
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
gradle run
go mod tidy
go run script-transfer-hbar.go
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.2001 ℏ
{ 2 } Credit new account 0.0.2012 ℏ
{ 3 } Node fee is paid to account 0.0.40.00007032 ℏ