Unicorn Ultra
  • Welcome to unicorn ultra — let’s build the future
  • Getting Started
    • Introduction
    • Environment Setup
    • Create an Account
    • Transfer U2U
    • Query Ledger Data
  • Tutorials
    • Smart Contracts
      • Deploy Your First Smart Contract
      • Deploy a Contract Using the Hedera Token Service
      • Send and Receive HBAR Using Solidity Smart Contracts
      • Create an HBAR Faucet App Using React and MetaMask
      • Deploy By Leveraging Ethereum Developer Tools On Hedera
      • Deploy a Smart Contract Using Hardhat
      • Deploy a Subgraph Using The Graph and JSON-RPC
      • How to Set Up Foundry to Test Smart Contracts on Hedera
      • Deploy Smart Contracts on Hedera Using Truffle
    • 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
    • More Tutorials
      • 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 Arkhia RPC endpoints
        • Configuring Hedera JSON-RPC Relay endpoints
    • Demo Applications
    • Starter Projects
  • Networks
    • Mainnet
      • Mainnet Accounts
      • Mainnet Consensus Nodes
        • Node Requirements
          • Reference Configuration
          • FAQ
      • Fees
        • Transaction Records
    • Testnets
      • Testnet Accounts
      • Testnet Consensus Nodes
    • Network Explorers and Tools
    • Release Notes
      • Hedera Services
      • Hedera Mirror Node
  • Core Concepts
    • Accounts
      • Account Creation
      • Auto Account Creation
      • Account Properties
    • Keys and Signatures
    • Scheduled Transaction
    • Smart Contracts
      • Hyperledger Besu EVM
      • Gas and Fees
      • Solidity Variables and Opcodes
      • Supported ERC Token Standards
      • Hedera Services Integration with Smart Contracts
      • JSON-RPC Relay
      • Hethers
      • Smart Contract Security
    • Staking
      • Staking Program
      • Stake HBAR
    • Hashgraph Consensus Algorithm
      • Gossip About Gossip
      • Virtual Voting
    • Transactions and Queries
    • 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)
      • Hedera ETL
  • 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
        • 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 scheduled transaction
        • Sign a scheduled transaction
        • Delete a scheduled transaction
        • Get schedule info
        • Network Response Messages
        • Schedule FAQ
      • 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
        • Transfer tokens
        • 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
    • REST API
    • 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
    • Deprecated
      • SDKs (V1)
        • 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
        • Hbars
        • Specialized Types
        • Pseudorandom Number Generator
        • Transactions
          • 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
        • Scheduled Transaction
          • Schedule ID
          • Create a scheduled transaction
          • Sign a scheduled transaction
          • Delete a scheduled transaction
          • Get schedule info
          • Network Response Messages
          • Schedule FAQ
        • 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
        • Token Service
          • Token ID
          • NFT ID
          • Token types
          • Create a token
          • Custom token fees
          • Update a token
          • Update token custom fees
          • Transfer tokens
          • 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
  • Support & Community
    • Glossary
    • Discord
    • GitHub
    • Stack Overflow
    • Hedera Blog
    • Bug Bounty
    • Hedera Help
    • Meetups
    • Contributing Guide
    • Brand Guidelines
    • Status Page
Powered by GitBook
On this page
  • Summary
  • Prerequisites
  • Step 1: Create your project directory
  • Step 2: Install Dependencies and SDKs
  • Step 3: Create your .env File
  • Step 4: Create your Hedera Testnet client
  • Code Check
  1. Getting Started

Environment Setup

PreviousIntroductionNextCreate an Account

Last updated 1 year ago

Summary

This environment setup guide will provide you with the necessary steps to get your development environment ready for building applications on the Hedera Network. You will set up a new project directory, establish a .env environment variable file to store your Hedera Testnet account ID and private keys and configure your Hedera Testnet client.

Prerequisites

Note: You can always check the " " 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 community or on the GitHub repository .

Step 1: Create your project directory

Open your IDE of choice and follow the below steps to create your new project directory.

Create a new Gradle project and name it HederaExamples. Add the following dependencies to your build.gradle file.

build.gradle
dependencies {

    implementation 'com.hedera.hashgraph:sdk:2.19.0'
    implementation 'io.grpc:grpc-netty-shaded:1.46.0'
    implementation 'io.github.cdimascio:dotenv-java:2.3.2'
    implementation 'org.slf4j:slf4j-nop:2.0.3'
    implementation 'com.google.code.gson:gson:2.8.8'

}

Open your terminal and create a directory called hello-hedera-js-sdk. After you create the project directory navigate to the directory by running the following command:

mkdir hello-hedera-js-sdk && cd hello-hedera-js-sdk

Initialize a node.js project in this new directory by running the following command:

npm init -y

This is what your console should look like after running the command:

{
  "name": "hello-hedera-js-sdk",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Open your terminal and create a project directory called something like hedera-go-examples to store your Go source code.

mkdir hedera-go-examples && cd hedera-go-examples

Step 2: Install Dependencies and SDKs

Create a new Java class and name it something like HederaExamples. Import the following classes to use in your example:

import com.hedera.hashgraph.sdk.AccountId;
import com.hedera.hashgraph.sdk.Client;
import com.hedera.hashgraph.sdk.PrivateKey;
import io.github.cdimascio.dotenv.Dotenv;
import com.hedera.hashgraph.sdk.HederaPreCheckStatusException;
import com.hedera.hashgraph.sdk.HederaReceiptStatusException;
import com.hedera.hashgraph.sdk.TransactionResponse;
import com.hedera.hashgraph.sdk.TransferTransaction;
import com.hedera.hashgraph.sdk.PublicKey;
import com.hedera.hashgraph.sdk.AccountCreateTransaction;
import com.hedera.hashgraph.sdk.Hbar;
import com.hedera.hashgraph.sdk.AccountBalanceQuery;
import com.hedera.hashgraph.sdk.AccountBalance;

import java.util.concurrent.TimeoutException;
// Install Hedera's JS SDK with NPM
npm install --save @hashgraph/sdk

// Install with Yarn
yarn add @hashgraph/sdk

Install dotenv with your favorite package manager. This will allow our node environment to use your testnet account ID and the private key we will store in a .env file next.

// Install with NPM
npm install dotenv

// Install with Yarn
yarn add dotenv

Navigate to the project root directory and create a index.js file by running the following command:

touch index.js

Your project structure should look something like this:

Create a hedera_examples.go file in hedera-go-examples directory. You will write all of your code in this file.

Import the following packages to your hedera_examples.go file:

package main

import (
    "fmt"
    "os"

    "github.com/joho/godotenv"
    "github.com/hashgraph/hedera-sdk-go/v2"
)

Step 3: Create your .env File

Create the .env file in your project's root directory. The .env file stores your environment variables, account ID, and private key (DER encoded).

MY_ACCOUNT_ID=ENTER TESTNET ACCOUNT ID 
MY_PRIVATE_KEY=ENTER TESTNET PRIVATE KEY

Next, you will load your account ID and private key variables from the .env file created in the previous step.

Within the main method, add your testnet account ID and private key from the environment file.

HederaExamples.java
public class HederaExamples {

    public static void main(String[] args) {

        //Grab your Hedera Testnet account ID and private key
        AccountId myAccountId = AccountId.fromString(Dotenv.load().get("MY_ACCOUNT_ID"));
        PrivateKey myPrivateKey = PrivateKey.fromString(Dotenv.load().get("MY_PRIVATE_KEY"));  
    }
}
index.js
const { Client, PrivateKey, AccountCreateTransaction, AccountBalanceQuery, Hbar, TransferTransaction } = require("@hashgraph/sdk");
require('dotenv').config();

async function environmentSetup() {

    //Grab your Hedera testnet account ID and private key from your .env file
    const myAccountId = process.env.MY_ACCOUNT_ID;
    const myPrivateKey = process.env.MY_PRIVATE_KEY;

    // If we weren't able to grab it, we should throw a new error
    if (!myAccountId || !myPrivateKey) {
        throw new Error("Environment variables MY_ACCOUNT_ID and MY_PRIVATE_KEY must be present");
    }
}
environmentSetup();
hedera_examples.go
func main() {

    //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)
    }

    //Print your testnet account ID and private key to the console to make sure there was no error
    fmt.Printf("The account ID is = %v\n", myAccountId)
    fmt.Printf("The private key is = %v\n", myPrivateKey)
}

In your terminal, enter the following command to create your go.mod file. This module is used for tracking dependencies and is required.

go mod init hedera_examples.go

Run your code to see your testnet account ID and private key printed to the console.

go run hedera_examples.go

Step 4: Create your Hedera Testnet client

To avoid encountering the INSUFFICIENT_TX_FEE error while conducting transactions, you can adjust the maximum transaction fee limit through the .setDefaultMaxTransactionFee() method. Similarly, the maximum query payment can be adjusted using the .setDefaultMaxQueryPayment() method.

🚨 How to resolve the INSUFFIENT_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:

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:

client.setDefaultMaxTransactionFee(maxTransactionFee);
//Create your Hedera Testnet client
Client client = Client.forTestnet();

//Set your account as the client's operator
client.setOperator(myAccountId, myPrivateKey);

//Set the default maximum transaction fee (in Hbar)
client.setDefaultMaxTransactionFee(new Hbar(100));

//Set the maximum payment for queries (in Hbar)
client.setMaxQueryPayment(new Hbar(50));
//Create your Hedera Testnet client
const client = Client.forTestnet();

//Set your account as the client's operator
client.setOperator(myAccountId, myPrivateKey);

//Set the default maximum transaction fee (in Hbar)
client.setDefaultMaxTransactionFee(new Hbar(100));

//Set the maximum payment for queries (in Hbar)
client.setMaxQueryPayment(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))

Your project environment is now set up to submit transactions and queries to the Hedera test network successfully!

Java
HederaExamples.java
import com.hedera.hashgraph.sdk.AccountId;
import com.hedera.hashgraph.sdk.Client;
import com.hedera.hashgraph.sdk.PrivateKey;
import io.github.cdimascio.dotenv.Dotenv;
import com.hedera.hashgraph.sdk.HederaPreCheckStatusException;
import com.hedera.hashgraph.sdk.HederaReceiptStatusException;
import com.hedera.hashgraph.sdk.TransactionResponse;
import com.hedera.hashgraph.sdk.TransferTransaction;
import com.hedera.hashgraph.sdk.PublicKey;
import com.hedera.hashgraph.sdk.AccountCreateTransaction;
import com.hedera.hashgraph.sdk.Hbar;
import com.hedera.hashgraph.sdk.AccountBalanceQuery;
import com.hedera.hashgraph.sdk.AccountBalance;

import java.util.concurrent.TimeoutException;
​
public class HederaExamples {
​
    public static void main(String[] args) {
​
        //Grab your Hedera Testnet account ID and private key
        AccountId myAccountId = AccountId.fromString(Dotenv.load().get("MY_ACCOUNT_ID"));+
        PrivateKey myPrivateKey = PrivateKey.fromString(Dotenv.load().get("MY_PRIVATE_KEY"));
​
        //Create your Hedera Testnet client
        Client client = Client.forTestnet();
        client.setOperator(myAccountId, myPrivateKey);
        
        // Set default max transaction fee & max query payment
        client.setDefaultMaxTransactionFee(new Hbar(100)); 
        client.setMaxQueryPayment(new Hbar(50)); 
    }
}
JavaScript
index.js
const {
  Client,
  PrivateKey,
  AccountCreateTransaction,
  AccountBalanceQuery,
  Hbar,
  TransferTransaction,
} = require("@hashgraph/sdk");

require("dotenv").config();

async function environmentSetup() {
  //Grab your Hedera testnet account ID and private key from your .env file
  const myAccountId = process.env.MY_ACCOUNT_ID;
  const myPrivateKey = process.env.MY_PRIVATE_KEY;

  // If we weren't able to grab it, we should throw a new error
  if (!myAccountId || !myPrivateKey) {
    throw new Error(
      "Environment variables MY_ACCOUNT_ID and MY_PRIVATE_KEY must be present"
    );
  }
  
  //Create your Hedera Testnet client
  const client = Client.forTestnet();

  //Set your account as the client's operator
  client.setOperator(myAccountId, myPrivateKey);

  //Set the default maximum transaction fee (in Hbar)
  client.setDefaultMaxTransactionFee(new Hbar(100));

  //Set the maximum payment for queries (in Hbar)
  client.setMaxQueryPayment(new Hbar(50));
}
environmentSetup();
Go
hedera_examples.go
package main

import (
	"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 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))
}

Note: You may install the latest version of the Java SDK .

Install the with your favorite package manager npm or yarn by running the following command:

Note: Install the Go SDK and the DotEnv package before moving forward.

Note: Testnet HBAR is required for this next step. Please follow the instructions to create a Hedera account on the before you move on to the next step.

Grab the Hedera Testnet account ID and DER-encoded private key from your (see screenshot below) and assign them to the MY_ACCOUNT_ID and MY_PRIVATE_KEY environment variables in your .env file:

Create a Hedera Testnet and set the operator information using the testnet account ID and private key for transaction and query fee authorization. The operator is the default account that will pay for the transaction and query fees in HBAR. You will need to sign the transaction or query with the private key of that account to authorize the payment. In this case, the operator ID is your testnet account ID**.** and the operator private key is the corresponding testnet account private key.

Next, you will learn how to .

Code Check

Have a question?

✅
here
JavaScript SDK
here
here
portal
Hedera portal profile
create an account
Ask it on StackOverflow

INTRODUCTION

here
here
Code Check ✅
client
Hedera Developer Portal