Hedera
  • Welcome to Hedera — let’s build the future
  • Getting Started
    • Environment Setup
    • Web2 Developers
      • Transfer HBAR
      • Create a Token
      • Create a Topic
    • EVM Developers
      • Deploy a Contract
  • Tutorials
    • Smart Contracts
      • How to Mint & Burn an ERC-721 Token Using Hardhat and Ethers (Part 1)
      • How to Set Access Control, a Token URI, Pause, and Transfer an ERC-721 Token Using Hardhat (Part 2)
      • How to Upgrade an ERC-721 Token with OpenZeppelin UUPS Proxies and Hardhat (Part 3)
      • How to Verify a Smart Contract on HashScan
      • Deploy a Smart Contract Using Remix
      • Deploy a Smart Contract Using Hardhat and Hiero JSON-RPC Relay
      • Deploy Your First Smart Contract
      • Deploy a Contract Using the Hedera Token Service
      • Send and Receive HBAR Using Solidity Smart Contracts
      • Deploy By Leveraging Ethereum Developer Tools On Hedera
      • Deploy a Subgraph Using The Graph and Hedera JSON-RPC Relay
      • Deploy Smart Contracts on Hedera Using Truffle
      • The Power of Native Hedera Tokens as ERC-20 Tokens: A step-by-step guide
      • HTS x EVM - Part 1: How to Mint NFTs
      • HTS x EVM - Part 2: KYC & Update
      • HTS x EVM - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs
      • Hedera Smart Contracts Workshop
        • Setup
        • Solidity
        • Hedera SDK JS
        • Hardhat and EthersJs
        • Outro
      • Foundry
        • How to Setup Foundry and Write a Basic Unit Test
        • How to Deploy and Verify a Hedera Smart Contract with Foundry
        • How to Test A Solidity Event
        • How to Fork Testnet on Latest Block
    • Consensus
      • Submit Your First Message
      • Submit Message to Private Topic
      • Query Messages with Mirror Node
    • Tokens
      • Create and Transfer Your First NFT
      • Create and Transfer Your First Fungible Token
      • Create and Transfer an NFT using a Solidity Contract
      • Structure Your Token Metadata Using JSON Schema V2
      • Hedera Token Service - Part 1: How to Mint NFTs
      • Hedera Token Service - Part 2: KYC, Update, and Scheduled Transactions
      • Hedera Token Service - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs
      • Create Your First Frictionless Airdrop Campaign
    • Local Node
      • How to Run Hedera Local Node in a Cloud Development Environment (CDE)
        • Run a Local Node in Gitpod
        • Run a Local Node in Codespaces
      • How to Set Up a Hedera Local Node
      • Set Up a Hedera Local Node using the NPM CLI
    • More Tutorials
      • Create and Fund Your Hedera Testnet Account
      • How to Create a Personal Access Token (API Key) on the Hedera Portal
      • How to Auto-Create Hedera Accounts with HBAR and Token Transfers
      • How to Configure a Mirror Node and Query Data
      • How to Generate a Random Number on Hedera
      • Get Started with the Hedera Consensus Service Fabric Plugin
        • Virtual Environment Setup
      • Schedule Your First Transaction
      • How to Connect to Hedera Networks Over RPC
        • Configuring Hashio RPC endpoints
        • Configuring Hiero JSON-RPC Relay endpoints
        • Configuring Validation Cloud RPC endpoints
      • JavaScript Testing
      • Create a Hedera DApp Integrated with WalletConnect
      • How to Connect MetaMask to Hedera
    • Demo Applications
    • Starter Projects
    • Building on Hedera (course)
  • Networks
    • Mainnet
      • Mainnet Accounts
      • Mainnet Consensus Nodes
        • Node Requirements
          • FAQ
      • Fees
        • Transaction Records
    • Testnets
      • Testnet Accounts
      • Testnet Consensus Nodes
    • Localnet
      • Single Node Configuration
      • Multinode Configuration
    • Network Explorers and Tools
    • Release Notes
      • Consensus Node
      • Hedera Mirror Node
  • Core Concepts
    • Accounts
      • Account Creation
      • Auto Account Creation
      • Account Properties
    • Keys and Signatures
    • Schedule Transaction
    • Smart Contracts
      • Understanding Hedera's EVM Differences and Compatibility
        • For EVM Developers Migrating to Hedera
          • Accounts, Signature Verification & Keys (ECDSA vs. ED25519)
          • JSON-RPC Relay and EVM Tooling
          • Token Management with Hedera Token Service
          • Decimal Handling (8 vs. 18 Decimals)
          • Handling HBAR Transfers in Contracts
        • For Hedera-Native Developers Adding Smart Contract Functionality
          • Integrating ED25519 Accounts and Advanced Features Into Smart Contracts
          • JSON-RPC Relay and State Queries
          • Extending Token Management with Smart Contracts
      • Creating Smart Contracts
      • Compiling Smart Contracts
      • System Smart Contracts
        • Hedera Account Service
        • Hedera Schedule Service
      • Gas and Fees
      • JSON-RPC Relay
      • Deploying Smart Contracts
      • Smart Contract Addresses
      • Verifying Smart Contracts
      • Smart Contract Traceability
      • Tokens Managed by Smart Contracts
        • ERC-20 (Fungible Tokens)
        • ERC-721 (Non-Fungible Token)
        • ERC-3643 Real World Assets (RWA)
        • ERC-1363 (Payable Tokens)
        • Hedera Token Service System Contract
      • Wrapped HBAR (WHBAR)
      • Smart Contract Rent
      • Smart Contract Security
      • EVM Archive Node Queries
    • Tokens
      • Tokenization on Hedera
      • Hedera Token Service (HTS) Native Tokenization
        • Token Types and ID Formats
        • Token Properties
        • Token Creation
        • Custom Fee Schedule
        • Token Airdrops
      • ERC/EVM-Compatible Tokenization
      • Hybrid (HTS + EVM ) Tokenization
    • Staking
      • Staking Program
      • Stake HBAR
    • Hashgraph Consensus Algorithm
      • Gossip About Gossip
      • Virtual Voting
    • Transactions and Queries
      • Transaction Properties
    • State and History
    • Mirror Nodes
      • Hedera Mirror Node
      • One Click Mirror Node Deployment
      • Run Your Own Mirror Node
        • Run Your Own Mirror Node with Google Cloud Storage (GCS)
        • Run Your Mirror Node with Amazon Web Services S3 (AWS)
  • Open Source Solutions and Integrations
    • AI Tools for Developers
      • Hedera AI Agent Kit
      • ElizaOS Plugin for Hedera
      • Hedera Hivemind
      • Kapa AI
    • Asset Tokenization Studio (ATS)
      • Web User Interface (UI)
      • Frequently Asked Questions (FAQs)
    • HashioDAO
      • Governance Token DAO
      • NFT DAO
      • Multisig DAO
      • DAO Proposals
      • Local Environment Setup
    • Hedera CLI
    • Hedera Contract Builder
    • Hedera Custodians Library
      • How to use it
    • Hedera Developers Code Repository
    • Hedera Developer Playground
    • Hedera Wallet Snap By MetaMask
      • Hedera Wallet Snap Documentation
      • Tutorial: MetaMask Snaps – What Are They and How to Use Them
    • Interoperability and Bridging
      • LayerZero
    • NFT Studio
      • Airdrop List Verifier
      • Metadata Validator
      • NFT Rarity Inspector
      • NFT Token Holders List Builder
      • NFT Risk Calculator
      • Token Balance Snapshot
      • Hedera NFT SDK
    • Oracle Networks
      • Chainlink Oracles
      • Pyth Oracles
      • Supra Oracles
    • Stablecoin Studio
      • Core Concepts
      • Web UI Application
      • CLI Management
      • TypeScript SDK
    • Hedera Guardian
    • Hedera WalletConnect
  • SDKs & APIs
    • SDKs
      • Build Your Hedera Client
      • Set Up Your Local Network
      • Network Address Book
      • Keys
        • Generate a new key pair
        • Import an existing key
        • Create a key list
        • Create a threshold key
        • Generate a mnemonic phrase
        • Recover keys from a mnemonic phrase
      • HBAR
      • Specialized Types
      • Pseudorandom Number Generator
      • Transactions
        • Create a Batch Transaction
        • Transaction ID
        • Modify transaction fields
        • Create an unsigned transaction
        • Manually sign a transaction
        • Submit a transaction
        • Sign a multisignature transaction
        • Get a transaction receipt
        • Get a transaction record
      • Schedule Transaction
        • Schedule ID
        • Create a schedule transaction
        • Sign a scheduled transaction
        • Delete a schedule transaction
        • Get schedule info
        • Network Response Messages
      • Queries
      • General Network Response Messages
      • Accounts and HBAR
        • Create an account
        • Update an account
        • Transfer cryptocurrency
        • Approve an allowance
        • Delete an allowance
        • Delete an account
        • Get account balance
        • Get account info
        • Network Response Messages
      • Consensus Service
        • Create a topic
        • Update a topic
        • Submit a message
        • Delete a topic
        • Get topic messages
        • Get topic info
        • Network Response
      • Token Service
        • Token ID
        • NFT ID
        • Token types
        • Create a token
        • Custom token fees
        • Update a token
        • Update token custom fees
        • Update NFT metadata
        • Transfer tokens
        • Airdrop a token
        • Claim a token
        • Cancel a token
        • Reject a token
        • Delete a token
        • Mint a token
        • Burn a token
        • Freeze an account
        • Unfreeze an account
        • Enable KYC account flag
        • Disable KYC account flag
        • Associate tokens to an account
        • Dissociate tokens from an account
        • Pause a token
        • Unpause a token
        • Wipe a token
        • Atomic swaps
        • Get account token balance
        • Get token info
        • Get NFT info
        • Network Response Messages
      • File Service
        • Create a file
        • Append to a file
        • Update a file
        • Delete a file
        • Get file contents
        • Get file info
        • Network Response Messages
      • Smart Contract Service
        • Delegate Contract ID
        • Create a smart contract
        • Update a smart contract
        • Delete a smart contract
        • Call a smart contract function
        • Ethereum transaction
        • Get a smart contract function
        • Get smart contract bytecode
        • Get smart contract info
        • Hedera Service Solidity Libraries
        • Network Response Messages
      • Signature Provider
        • Provider
        • Signer
        • Wallet
        • Local Provider
    • Mirror Node REST API
      • Accounts
      • Balances
      • Blocks
      • Schedule Transactions
      • Smart Contracts
      • Tokens
      • Topics
      • Transactions
      • Network
    • Hedera Consensus Service gRPC API
    • Hedera APIs
      • Basic Types
        • AccountAmount
        • AccountID
        • ContractID
        • CryptoAllowance
        • CurrentAndNextFeeSchedule
        • FeeComponents
        • FeeData
        • FeeSchedule
        • FileID
        • Fraction
        • HederaFunctionality
        • Key
        • KeyList
        • NftAllowance
        • NftTransfer
        • NodeAddress
        • NodeAddressBook
        • RealmID
        • ScheduleID
        • SemanticVersion
        • ServicesConfigurationList
        • ServiceEndpoint
        • Setting
        • ShardID
        • Signature
        • SignatureList
        • SignatureMap
        • SignaturePair
        • SubType
        • TransferList
        • TransactionID
        • ThresholdKey
        • ThresholdSignature
        • TokenAllowance
        • TokenBalance
        • TokenBalances
        • TokenFreezeStatus
        • TokenPauseStatus
        • TokenID
        • TokenKycStatus
        • TokenRelationship
        • TokenTransferList
        • TokenType
        • TokenSupplyType
        • TopicID
        • TransactionFeeSchedule
      • Cryptocurrency Accounts
        • CryptoService
        • CryptApproveAllowance
        • CryptoDeleteAllowance
        • CryptoCreate
        • CryptoTransfer
        • CryptoUpdate
        • CryptoDelete
        • CryptoGetAccountBalance
        • CryptoGetAccountRecords
        • CryptoGetInfo
        • CryptoGetStakers
      • Consensus Service
        • Consensus Service
        • ConsensusCreateTopic
        • ConsensusUpdateTopic
        • ConsensusSubmitMessage
        • ConsensusDeleteTopic
        • ConsensusTopicInfo
        • ConsensusGetTopicInfo
      • Schedule Service
        • ScheduleService
        • SchedulableTransactionBody
        • ScheduleCreate
        • ScheduleDelete
        • ScheduleSign
        • ScheduleGetInfo
      • Token Service
        • TokenService
        • CustomFees
          • AssessedCustomFee
          • CustomFee
          • FractionalFee
          • FixedFee
          • RoyaltyFee
        • TokenCreate
        • TokenUpdate
        • TokenFeeScheduleUpdate
        • TokenDelete
        • TokenMint
        • TokenBurn
        • TokenFreezeAccount
        • TokenUnfreezeAccount
        • TokenGrantKyc
        • TokenRevokeKyc
        • TokenAssociate
        • TokenDissociate
        • TokenWipeAccount
        • TokenPause
        • TokenUnpause
        • TokenGetInfo
        • TokenGetNftInfo
        • TokenGetNftInfos
        • TokenGetAccountNftInfo
      • File Service
        • FileService
        • FileCreate
        • FileAppend
        • FileUpdate
        • FileDelete
        • FileGetContents
        • FileGetInfo
      • Smart Contracts
        • SmartContractService
        • ContractCall
        • ContractCallLocal
        • ContractCreate
        • ContractUpdate
        • ContractDelete
        • ContractGetByteCode
        • ContractGetInfo
        • ContractGetRecords
      • Miscellaneous
        • Duration
        • ExchangeRate
        • Freeze
        • FreezeType
        • GetByKey
        • GetBySolidityID
        • NetworkGetVersionInfo
        • NetworkService
        • Query
        • QueryHeader
        • Response
        • ResponseCode
        • ResponseHeader
        • SystemDelete
        • SystemUndelete
        • TimeStamp
        • Transaction
        • TransactionBody
        • TransactionContents
        • TransactionGetFastRecord
        • TransactionGetReceipt
        • TransactionGetRecord
        • TransactionReceipt
        • TransactionRecord
        • TransactionResponse
        • UncheckedSubmit
    • Hedera Status API
  • Support & Community
    • Glossary
    • Contributing to Hedera documentation
      • Contribution Guidelines
        • Creating Issues
        • Creating Pull Requests
        • Hedera Improvement Proposal (HIP)
        • Submit Demo Applications
      • Style Guide
        • Understanding different types of documentation
        • Use of HBAR and tinybars
        • Use of web2 and web3
        • Language and grammar
        • Formatting
        • Punctuation
        • GitBook Markdown Syntax
    • Discord
    • GitHub
    • Stack Overflow
    • Hedera Blog
    • Bug Bounty
    • Hedera Help
    • Documentation Survey
    • Meetups
    • Brand Guidelines
    • Status Page
Powered by GitBook
LogoLogo

INTRODUCTION

  • Fees
  • Core Concepts
  • Network Information

TOOLS

  • Bridge
  • Oracles
  • Explorers
  • Developer Portal & Faucet

RESOURCES

  • Status
  • Bug Bounty
  • Build on Hedera (course)
  • Documentation Survey
On this page
  • Introduction to Transferring HBAR
  • Prerequisites
  • Step 1: Navigate to the transfer example in the project directory
  • Step 2: Guided Code Walkthrough
  • Create a Hedera Testnet Client
  • Create a Transfer Transaction
  • Sign the Transfer Transaction
  • Query the Account Balance
  • Query the Transfer Transaction via Mirror Node API
  • Step 3: Run the Transfer Transaction Script
  • View the Transfer Transaction and Transaction Fees in HashScan
  • Code Check ✅
  • Complete
  • Next Steps

Was this helpful?

Edit on GitHub
  1. Getting Started
  2. Web2 Developers

Transfer HBAR

PreviousWeb2 DevelopersNextCreate a Token

Last updated 1 month ago

Was this helpful?

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 ../

Step 2: Guided Code Walkthrough

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);
}
script-transfer-hbar.js
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:

Copy

client.setDefaultMaxTransactionFee(maxTransactionFee);

Create a Transfer Transaction

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

  • 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;
script-transfer-hbar.js
const transferTxVerifyMirrorNodeApiUrl = 
    `https://testnet.mirrornode.hedera.com/api/v1/transactions/
    ${transferTxIdMirrorNodeFormat}`;
script-transfer-hbar.go
transferTxVerifyMirrorNodeApiUrl :=
    fmt.Sprintf(
    "https://testnet.mirrornode.hedera.com/api/v1/transactions/%s?nonce=0", 
        transferTxIdMirrorNodeFormat)
Learn more about Mirror Node APIs

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:


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.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.

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

Open the transfer HBAR script (e.g., /transfer/script-transfer-hbar...) in a code editor like , , or a 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.

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

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.

You can explore the Mirror Node APIs interactively via its Swagger page: .

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

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

Have questions? Join the and post them in the channel or ask on .

Create and Fund Your Hedera Testnet Account
Environment Setup
VS Code
IntelliJ
Gitpod
fees table
Get Your Testnet Account
Mirror nodes
Hedera Testnet Mirror Node REST API
REST API
fees
Java
JavaScript
Go
Hedera Discord
developer-general
Stack Overflow
here

Create a Token

Create a Topic

Learn how to create fungible tokens using the (HTS).

Learn how to create topics and publish messages using the (HCS).

LEARN MORE
LEARN MORE
Transfer transaction in HashScan, with annotated items to check.
Hedera Token Service
Hedera Consensus Service