Note: You can always check the "Code Check ✅" section at the bottom of each page to view the entire code if you run into issues. You can also post your issue to the respective SDK channel in our Discord communityhereor on the GitHub repositoryhere.
Step 1. Create a transfer transaction
Use your new account created in the "Create an account" section and transfer 1,000 tinybars from your account to the new account. The account sending the HBAR needs to sign the transaction using its private keys to authorize the transfer. Since you are transferring from the account associated with the client, you do not need to explicitly sign the transaction as the operator account(account transferring the HBAR) signs all transactions to authorize the payment of the transaction fee.
//System.out.println("The new account balance is: " +accountBalance.hbars);//-----------------------<enter code below>--------------------------------------//Transfer HBARTransactionResponse sendHbar =newTransferTransaction().addHbarTransfer(myAccountId,Hbar.fromTinybars(-1000)) //Sending account.addHbarTransfer(newAccountId,Hbar.fromTinybars(1000)) //Receiving account.execute(client);
//console.log("The new account balance is: " +accountBalance.hbars.toTinybars() +" tinybar.");//-----------------------<enter code below>--------------------------------------//Create the transfer transactionconstsendHbar=awaitnewTransferTransaction().addHbarTransfer(myAccountId,Hbar.fromTinybars(-1000)) //Sending account.addHbarTransfer(newAccountId,Hbar.fromTinybars(1000)) //Receiving account.execute(client);
//Print the balance of tinybars//fmt.Println("The account balance for the new account is ", accountBalance.Hbars.AsTinybar())//-----------------------<enter code below>--------------------------------------//Transfer hbar from your testnet account to the new accounttransaction :=hedera.NewTransferTransaction().AddHbarTransfer(myAccountId,hedera.HbarFrom(-1000,hedera.HbarUnits.Tinybar)).AddHbarTransfer(newAccountId,hedera.HbarFrom(1000,hedera.HbarUnits.Tinybar))//Submit the transaction to a Hedera networktxResponse, err :=transaction.Execute(client)if err != nil {panic(err)}
Note: The net value of the transfer must equal zero (the total number ofHBARsent by the sender must equal the total number ofHBARreceived by the recipient).
Step 2. Verify the transfer transaction reached consensus
To verify the transfer transaction reached consensus by the network, you will submit a request to obtain the receipt of the transaction. The receipt status will let you know if the transaction was successful (reached consensus) or not.
System.out.println("The transfer transaction was: "+sendHbar.getReceipt(client).status);
//Verify the transaction reached consensusconsttransactionReceipt=awaitsendHbar.getReceipt(client);console.log("The transfer transaction from my account to the new account was: " + transactionReceipt.status.toString());
//Request the receipt of the transactiontransferReceipt, err :=txResponse.GetReceipt(client)if err != nil {panic(err)}//Get the transaction consensus statustransactionStatus :=transferReceipt.Statusfmt.Printf("The transaction consensus status is %v\n", transactionStatus)
Code Check ✅
Your complete code file should look something like this:
Java
HederaExamples.java
importcom.hedera.hashgraph.sdk.Hbar;importcom.hedera.hashgraph.sdk.Client;importio.github.cdimascio.dotenv.Dotenv;importcom.hedera.hashgraph.sdk.AccountId;importcom.hedera.hashgraph.sdk.PublicKey;importcom.hedera.hashgraph.sdk.PrivateKey;importcom.hedera.hashgraph.sdk.AccountBalance;importcom.hedera.hashgraph.sdk.AccountBalanceQuery;importcom.hedera.hashgraph.sdk.TransferTransaction;importcom.hedera.hashgraph.sdk.TransactionResponse;importcom.hedera.hashgraph.sdk.ReceiptStatusException;importcom.hedera.hashgraph.sdk.PrecheckStatusException;importcom.hedera.hashgraph.sdk.AccountCreateTransaction;importjava.util.concurrent.TimeoutException;publicclassHederaExamples { public static void main(String[] args) throws TimeoutException, HederaPreCheckStatusException, HederaReceiptStatusException {
//Grab your Hedera testnet account ID and private keyAccountId myAccountId =AccountId.fromString(Dotenv.load().get("MY_ACCOUNT_ID"));PrivateKey myPrivateKey =PrivateKey.fromString(Dotenv.load().get("MY_PRIVATE_KEY"));// Create your connection to the Hedera networkconst client =Client.forTestnet();//Set your account as the client's operator client.setOperator(myAccountId, myPrivateKey);// Set default max transaction fee & max query payment client.setDefaultMaxTransactionFee(newHbar(100)); client.setDefaultMaxQueryPayment(newHbar(50));// Generate a new key pairPrivateKey newAccountPrivateKey = PrivateKey.generateED25519();PublicKey newAccountPublicKey = newAccountPrivateKey.getPublicKey();//Create new account and assign the public keyTransactionResponse newAccount = new AccountCreateTransaction() .setKey(newAccountPublicKey) .setInitialBalance( Hbar.fromTinybars(1000)) .execute(client);// Get the new account IDAccountId newAccountId =newAccount.getReceipt(client).accountId; System.out.println("\nNew account ID: " +newAccountId);//Check the new account's balanceAccountBalance accountBalance =newAccountBalanceQuery().setAccountId(newAccountId).execute(client);//Transfer HBARTransactionResponse sendHbar =newTransferTransaction().addHbarTransfer(myAccountId,Hbar.fromTinybars(-1000)).addHbarTransfer(newAccountId,Hbar.fromTinybars(1000)).execute(client); System.out.println("The transfer transaction was: " +sendHbar.getReceipt(client).status); }}
JavaScript
index.js
const {Hbar,Client,PrivateKey,AccountBalanceQuery,TransferTransaction,AccountCreateTransaction,} =require("@hashgraph/sdk");require("dotenv").config();asyncfunctionenvironmentSetup() {// Grab your Hedera testnet account ID and private key from your .env fileconstmyAccountId=process.env.MY_ACCOUNT_ID;constmyPrivateKey=process.env.MY_PRIVATE_KEY;// // If we weren't able to grab it, we should throw a new errorif (myAccountId ==null|| myPrivateKey ==null) {thrownewError("Environment variables myAccountId and myPrivateKey must be present" ); }// Create your connection to the Hedera networkconstclient=Client.forTestnet();//Set your account as the client's operatorclient.setOperator(myAccountId, myPrivateKey);// Set default max transaction fee & max query paymentclient.setDefaultMaxTransactionFee(newHbar(100));client.setDefaultMaxQueryPayment(newHbar(50));// Create new keysconstnewAccountPrivateKey=PrivateKey.generateED25519();constnewAccountPublicKey=newAccountPrivateKey.publicKey;// Create a new account with 1,000 tinybar starting balanceconstnewAccountTransactionResponse=awaitnewAccountCreateTransaction().setKey(newAccountPublicKey).setInitialBalance(Hbar.fromTinybars(1000)).execute(client);// Get the new account IDconstgetReceipt=awaitnewAccountTransactionResponse.getReceipt(client);constnewAccountId=getReceipt.accountId;console.log("\nNew account ID: "+ newAccountId);// Verify the account balanceconstaccountBalance=awaitnewAccountBalanceQuery().setAccountId(newAccountId).execute(client);console.log("\nNew account balance is: "+accountBalance.hbars.toTinybars() +" tinybars." );// Create the transfer transactionconstsendHbar=awaitnewTransferTransaction().addHbarTransfer(myAccountId,Hbar.fromTinybars(-1000)).addHbarTransfer(newAccountId,Hbar.fromTinybars(1000)).execute(client);// Verify the transaction reached consensusconsttransactionReceipt=awaitsendHbar.getReceipt(client);console.log("\nThe transfer transaction from my account to the new account was: "+transactionReceipt.status.toString() );}environmentSetup();
Go
packagemainimport ("fmt""os""github.com/hashgraph/hedera-sdk-go/v2""github.com/joho/godotenv")funcmain() {//Loads the .env file and throws an error if it cannot load the variables from that file correctly err := godotenv.Load(".env")if err !=nil {panic(fmt.Errorf("Unable to load environment variables from .env file. Error:\n%v\n", err)) }//Grab your testnet account ID and private key from the .env file myAccountId, err := hedera.AccountIDFromString(os.Getenv("MY_ACCOUNT_ID"))if err !=nil {panic(err) } myPrivateKey, err := hedera.PrivateKeyFromString(os.Getenv("MY_PRIVATE_KEY"))if err !=nil {panic(err) }//Create your testnet client client := hedera.ClientForTestnet() client.SetOperator(myAccountId, myPrivateKey)// Set default max transaction fee & max query payment client.SetDefaultMaxTransactionFee(hedera.HbarFrom(100, hedera.HbarUnits.Hbar)) client.SetDefaultMaxQueryPayment(hedera.HbarFrom(50, hedera.HbarUnits.Hbar))//Generate new keys for the account you will create newAccountPrivateKey, err := hedera.PrivateKeyGenerateEd25519()if err !=nil {panic(err) } newAccountPublicKey := newAccountPrivateKey.PublicKey()//Create new account and assign the public key newAccount, err := hedera.NewAccountCreateTransaction().SetKey(newAccountPublicKey).SetInitialBalance(hedera.HbarFrom(1000, hedera.HbarUnits.Tinybar)).Execute(client)//Request the receipt of the transaction receipt, err := newAccount.GetReceipt(client)if err !=nil {panic(err) }//Get the new account ID from the receipt newAccountId :=*receipt.AccountID//Print the new account ID to the console fmt.Printf("The new account ID is %v\n", newAccountId)//Create the account balance query query := hedera.NewAccountBalanceQuery().SetAccountID(newAccountId)//Sign with client operator private key and submit the query to a Hedera network accountBalance, err := query.Execute(client)if err !=nil {panic(err) }//Print the balance of tinybars fmt.Println("The account balance for the new account is", accountBalance.Hbars.AsTinybar())//Transfer hbar from your testnet account to the new account transaction := hedera.NewTransferTransaction().AddHbarTransfer(myAccountId, hedera.HbarFrom(-1000, hedera.HbarUnits.Tinybar)).AddHbarTransfer(newAccountId, hedera.HbarFrom(1000, hedera.HbarUnits.Tinybar))//Submit the transaction to a Hedera network txResponse, err := transaction.Execute(client)if err !=nil {panic(err) }//Request the receipt of the transaction transferReceipt, err := txResponse.GetReceipt(client)if err !=nil {panic(err) }//Get the transaction consensus status transactionStatus := transferReceipt.Status fmt.Printf("The transaction consensus status is %v\n", transactionStatus)}