In this section, you will learn how to transfer hbar from your account to another account on the Hedera test network.
Note: This example uses Hedera Go SDK v2.0. The latest Hedera Go SDK version can be found here, however may not be compatible with this tutorial.
You should already have a new account ID from the account you created in the "Create an account" section. You will transfer 1,000 tinybars from your testnet account to the new account. The sender account's private key is required to sign the transaction. The sender account is your testnet account so the client is already set-up to sign with yout testnet account's private key to authorize the transfer.
//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)}
The net value of the transfer must equal zero (total number of hbars sent by the sender must equal the total number of hbars received by the recipient).
To verify the transfer transaction reached consensus by the network, you will submit a request to obtain the receipt of the transfer transaction. The receipt will let you know if the transaction was successful or not.
//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)
You can request the cost of a query prior to submitting the query to the Hedera network. Checking an account balance is free of charge today. You can verify that by the method below.
//Create the query that you want to submitbalanceQuery := hedera.NewAccountBalanceQuery().SetAccountID(newAccountId)//Get the cost of the querycost, err := balanceQuery.GetCost(client)if err != nil {panic(err)}println("The account balance query cost is:", cost.String())
You will verify the account balance was updated for the new account by submitting a get account balance query. The current account balance should be the sum of the initial balance (1,000 tinybar) plus the transfer amount (1,000 tinybar) and equal to 2,000 tinybars.
//Check the new account's balancenewAccountBalancequery := hedera.NewAccountBalanceQuery().SetAccountID(newAccountId)//Sign with client operator private key and submit the query to a Hedera networknewAccountBalance, err := newAccountBalancequery.Execute(client)if err != nil {panic(err)}//Print the balance of tinybarsfmt.Println("The hbar account balance for this account is", newAccountBalance.Hbars.AsTinybar())
⭐ Congratulations! You have successfully transferred hbars to another account on the Hedera testnet! If you have followed the tutorial from the beginning, you have completed the following thus far:
Set-up your Hedera environment to submit transactions and queries
Created an account
Transferred hbars to another account
Do you want to keep learning? Visit our "Resources" and "Documentation" section to take your learning experience to the next level. You can also find additional Hedera Go SDK examples here.
Your complete code file should look something like this:
package mainimport ("fmt""os""github.com/hashgraph/hedera-sdk-go/v2""github.com/joho/godotenv")func main() {//Loads the .env file and throws an error if it cannot load the variables from that file corectlyerr := godotenv.Load(".env")if err != nil {panic(fmt.Errorf("Unable to load enviroment variables from .env file. Error:\n%v\n", err))}//Grab your testnet account ID and private key from the .env filemyAccountId, 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)}//Print your testnet account ID and private key to the console to make sure there was no errorfmt.Printf("The account ID is = %v\n", myAccountId)fmt.Printf("The private key is = %v\n", myPrivateKey)//Create your testnet clientclient := hedera.ClientForTestnet()client.SetOperator(myAccountId, myPrivateKey)//Generate new keys for the account you will createnewAccountPrivateKey, err := hedera.GeneratePrivateKey()if err != nil {panic(err)}newAccountPublicKey := newAccountPrivateKey.PublicKey()//Create new account and assign the public keynewAccount, err := hedera.NewAccountCreateTransaction().SetKey(newAccountPublicKey).SetInitialBalance(hedera.HbarFrom(1000, hedera.HbarUnits.Tinybar)).Execute(client)//Request the receipt of the transactionreceipt, err := newAccount.GetReceipt(client)if err != nil {panic(err)}//Get the new account ID from the receiptnewAccountId := *receipt.AccountID//Print the new account ID to the consolefmt.Printf("The new account ID is %v\n", newAccountId)//Create the account balance queryquery := hedera.NewAccountBalanceQuery().SetAccountID(newAccountId)//Sign with client operator private key and submit the query to a Hedera networkaccountBalance, err := query.Execute(client)if err != nil {panic(err)}//Print the balance of tinybarsfmt.Println("The account balance for the new account is", accountBalance.Hbars.AsTinybar())//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)}//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)//Create the query that you want to submitbalanceQuery := hedera.NewAccountBalanceQuery().SetAccountID(newAccountId)//Get the cost of the querycost, err := balanceQuery.GetCost(client)if err != nil {panic(err)}fmt.Println("The account balance query cost is:", cost.String())//Check the new account's balancenewAccountBalancequery := hedera.NewAccountBalanceQuery().SetAccountID(newAccountId)//Sign with client operator private key and submit the query to a Hedera networknewAccountBalance, err := newAccountBalancequery.Execute(client)if err != nil {panic(err)}//Print the balance of tinybarsfmt.Println("The hbar account balance for this account is", newAccountBalance.Hbars.AsTinybar())}