Create an Account

Learn how to create a new Hedera account on testnet using the JavaScript, Java, or Go SDK. A Hedera account is your identity on‑chain. It holds your HBAR (the network’s currency) and lets you sign transactions.


Prerequisites

  • A Hedera testnet operator account ID and DER-encoded private key (from the Quickstart)

  • A small amount of testnet HBAR (ℏ) to pay the $0.05 account‑creation fee.

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


Install the SDK

Open your terminal and create a directory hedera-examples directory. Then change into the newly created directory:

mkdir hedera-examples && cd hedera-examples

Initialize a node.js project in this new directory:

npm init -y

Ensure you have Node.js v18 or later installed on your machine. Then, install the JavaScript SDK.

npm install --save @hashgraph/sdk

Update your package.json file to enable ES6 modules and configure the project:

{
  "name": "hedera-examples",
  "version": "1.0.0",
  "type": "module",
  "main": "createAccountDemo.js",
  "scripts": {
    "start": "node createAccountDemo.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@hashgraph/sdk": "^2.69.0"
  }
}

Create a createAccountDemo.js file and add the following imports:

import {
  Client,
  PrivateKey,
  AccountCreateTransaction,
  Hbar
} from "@hashgraph/sdk";

Environment Variables

Set your operator credentials as environment variables:

export OPERATOR_ID="0.0.1234"
export OPERATOR_KEY="302e020100300506032b657004220420..."

Step 1: Initialize Hedera Client

Load your operator credentials from environment variables and initialize your Hedera testnet client. This client will connect to the network and use your operator account to sign transactions and pay fees.

// Load your operator credentials
const operatorId  = process.env.OPERATOR_ID;
const operatorKey = process.env.OPERATOR_KEY;

// Initialize your testnet client and set operator
const client = Client.forTestnet()
    .setOperator(operatorId, operatorKey);

Step 2: Generate a New Key Pair

Generate a new ECDSA private/public key pair for the account you'll create.

Why keys?

On the Hedera network, a private key allows you to sign transactions, ensuring only you control your assets, while a public key, shared on-chain, verifies your identity. This key pair is essential for account security.

// Generates a new ECDSA key pair in memory
const newPrivateKey = PrivateKey.generateECDSA();
const newPublicKey = newPrivateKey.publicKey;

‼️ Security reminder: Keep your private keys secure - anyone with access can control your account and funds.


Step 3: Create Your First Account on Hedera

Build an AccountCreateTransaction with the new public key and initial balance, then execute it. Specify the key (or alias), an optional initial HBAR balance, and once you execute it, the network creates the account and returns the new AccountId in the receipt.

// Build & execute the account creation transaction
const transaction = new AccountCreateTransaction()
  .setKey(newPublicKey)                        // set the account key
  .setInitialBalance(new Hbar(20));            // fund with 20 HBAR

const txResponse = await transaction.execute(client);
const receipt = await txResponse.getReceipt(client);
const newAccountId = receipt.accountId;

console.log(`Hedera Account created: ${newAccountId}`);
console.log(`EVM Address: 0x${newPublicKey.toEvmAddress()}`);

Step 4: Query the Account Balance Using Mirror Node API

Use the Mirror Node REST API to check your new account's HBAR balance. Mirror nodes provide free access to network data without transaction fees.

API endpoint:

/api/v1/balances?account.id={accountId}

Replace the placeholder:

  • {accountId} - Your new account ID from the creation transaction

Why this endpoint?

This endpoint queries account balances directly by account ID. It returns detailed information including HBAR balance in tinybars, making it ideal for verifying the new account was funded with the expected initial balance.

Example URLs:

const mirrorNodeUrl = `https://testnet.mirrornode.hedera.com/api/v1/balances?account.id=${newAccountId}`;

Complete Implementation:

// Wait for Mirror Node to populate data
console.log("Waiting for Mirror Node to update...");
await new Promise(resolve => setTimeout(resolve, 6000));

// Query balance using Mirror Node
const mirrorNodeUrl = `https://testnet.mirrornode.hedera.com/api/v1/balances?account.id=${newAccountId}`;

const response = await fetch(mirrorNodeUrl );
const data = await response.json();

if (data.balances && data.balances.length > 0) {
  const balanceInTinybars = data.balances[0].balance;
  const balanceInHbar = balanceInTinybars / 100000000;
  console.log(`Account balance: ${balanceInHbar} ℏ`);
} else {
  console.log("Account balance not yet available in Mirror Node");
}

client.close();

✅ Code check

Before running your project, verify your code matches the complete example:

JavaScript
import {
  Client,
  PrivateKey,
  AccountCreateTransaction,
  Hbar
} from "@hashgraph/sdk";

async function createAccountDemo() {
  // 1. load your operator credentials
  const operatorId = process.env.OPERATOR_ID;
  const operatorKey = process.env.OPERATOR_KEY;

  // 2. initialize the client for testnet
  const client = Client.forTestnet()
    .setOperator(operatorId, operatorKey);

  // 3. generate a new key pair
  const newPrivateKey = PrivateKey.generateECDSA();
  const newPublicKey = newPrivateKey.publicKey;

  // 4. build & execute the account creation transaction
  const transaction = new AccountCreateTransaction()
    .setECDSAKeyWithAlias(newPublicKey)          // set the account key with alias
    .setInitialBalance(new Hbar(20));           // fund with 20 HBAR

  const txResponse = await transaction.execute(client);
  const receipt = await txResponse.getReceipt(client);
  const newAccountId = receipt.accountId;

  console.log(`\nHedera account created: ${newAccountId}`);
  console.log(`EVM Address: 0x${newPublicKey.toEvmAddress()}\n`);

  // Wait for Mirror Node to populate data
  console.log("Waiting for Mirror Node to update...\n");
  await new Promise(resolve => setTimeout(resolve, 6000));

  // 5. query balance using Mirror Node
  const mirrorNodeUrl = `https://testnet.mirrornode.hedera.com/api/v1/balances?account.id=${newAccountId}`;

  const response = await fetch(mirrorNodeUrl);
  const data = await response.json();

  if (data.balances && data.balances.length > 0) {
    const balanceInTinybars = data.balances[0].balance;
    const balanceInHbar = balanceInTinybars / 100000000;
    
    console.log(`Account balance: ${balanceInHbar} ℏ\n`);
  } else {
    console.log("Account balance not yet available in Mirror Node");
  }

  client.close();
}

createAccountDemo().catch(console.error);
Java
import com.hedera.hashgraph.sdk.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;

public class CreateAccountDemo {
    public static void main(String[] args) throws Exception {
        // 1. load your operator credentials
        String operatorId = System.getenv("OPERATOR_ID");
        String operatorKey = System.getenv("OPERATOR_KEY");

        // 2. initialize the client for testnet
        Client client = Client.forTestnet()
            .setOperator(AccountId.fromString(operatorId), PrivateKey.fromString(operatorKey));

        // 3. generate a new key pair
        PrivateKey newPrivateKey = PrivateKey.generateECDSA();
        PublicKey newPublicKey = newPrivateKey.getPublicKey();

        // 4. build & execute the account creation transaction
        AccountCreateTransaction transaction = new AccountCreateTransaction()
            // set the account key with alias
            .setECDSAKeyWithAlias(newPublicKey)          
            .setInitialBalance(new Hbar(20)); // fund with 20 HBAR           

        TransactionResponse txResponse = transaction.execute(client);
        TransactionReceipt receipt = txResponse.getReceipt(client);
        AccountId newAccountId = receipt.accountId;

        System.out.println("Hedera account created: " + newAccountId);
        System.out.println("EVM Address: 0x" + newPublicKey.toEvmAddress() + "\n");

        // Wait for Mirror Node to populate data
        System.out.println("Waiting for Mirror Node to update...\n");
        Thread.sleep(6000);

        // 5. query balance using Mirror Node
        String mirrorNodeUrl = "https://testnet.mirrornode.hedera.com/api/v1/balances?account.id=" + newAccountId;

        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(mirrorNodeUrl))
            .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        Gson gson = new Gson();
        JsonObject data = gson.fromJson(response.body(), JsonObject.class);

        if (data.has("balances") && data.getAsJsonArray("balances").size() > 0) {
            JsonArray balances = data.getAsJsonArray("balances");
            JsonObject accountBalance = balances.get(0).getAsJsonObject();
            long balanceInTinybars = accountBalance.get("balance").getAsLong();
            double balanceInHbar = balanceInTinybars / 100000000.0;
            
            System.out.println("Account balance: " + balanceInHbar + " ℏ");
        } else {
            System.out.println("Account balance not yet available in Mirror Node");
        }

        client.close();
    }
}
Go
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "time"

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

func main() {
    // 1. load your operator credentials
    operatorId, err := hedera.AccountIDFromString(os.Getenv("OPERATOR_ID"))
    if err != nil {
        panic(err)
    }

    operatorKey, err := hedera.PrivateKeyFromString(os.Getenv("OPERATOR_KEY"))
    if err != nil {
        panic(err)
    }

    // 2. initialize the client for testnet
    client := hedera.ClientForTestnet()
    client.SetOperator(operatorId, operatorKey)

    // 3. generate a new key pair
    newPrivateKey, err := hedera.PrivateKeyGenerateECDSA()
    if err != nil {
        panic(err)
    }
    newPublicKey := newPrivateKey.PublicKey()

    // 4. build & execute the account creation transaction
    transaction := hedera.NewAccountCreateTransaction().
        // set the account key with alias
        SetECDSAKeyWithAlias(newPublicKey).          
        SetInitialBalance(hedera.NewHbar(20)) // fund with 20 HBAR

    txResponse, err := transaction.Execute(client)
    if err != nil {
        panic(err)
    }

    receipt, err := txResponse.GetReceipt(client)
    if err != nil {
        panic(err)
    }

    newAccountId := *receipt.AccountID

    fmt.Printf("Hedera account created: %s\n", newAccountId.String())
    fmt.Printf("EVM Address: 0x%s\n", newPublicKey.ToEvmAddress())

    // Wait for Mirror Node to populate data
    fmt.Println("Waiting for Mirror Node to update...\n")
    time.Sleep(6 * time.Second)

    // 5. query balance using Mirror Node
    mirrorNodeUrl := "https://testnet.mirrornode.hedera.com/api/v1/balances?account.id=" + newAccountId.String()

    resp, err := http.Get(mirrorNodeUrl)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    var data struct {
        Balances []struct {
            Balance int64 `json:"balance"`
        } `json:"balances"`
    }

    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err)
    }

    if len(data.Balances) > 0 {
        balanceInTinybars := data.Balances[0].Balance
        balanceInHbar := float64(balanceInTinybars) / 100000000.0
        
        fmt.Printf("Account balance: %.8f ℏ", balanceInHbar)
    } else {
        fmt.Println("Account balance not yet available in Mirror Node")
    }

    client.Close(nil)
}

Run Your Project

Ensure your environment variables are set:

export OPERATOR_ID="0.0.1234"
export OPERATOR_KEY="302e020100300506032b657004220420..."
node createAccountDemo.js

Expected sample output:

Hedera account created: 0.0.12345
EVM Address: 0xabcdef0123456789abcdef0123456789abcdef01

Waiting for Mirror Node to update...

Account balance: 20 ℏ

‼️ Troubleshooting

Common ERROR messages and solutions ⬇️
Error message
Likely cause
Fix

INSUFFICIENT_PAYER_BALANCE

Operator account lacks enough ℏ for the fee.

Top‑up your testnet account with the HBAR faucet.

INVALID_SIGNATURE

Operator key doesn't match operator account

Verify OPERATOR_KEY matches your OPERATOR_ID

INVALID_ACCOUNT_ID

Malformed account ID in environment variables

Verify OPERATOR_ID format is 0.0.1234

INVALID_PRIVATE_KEY

Malformed private key in environment variables

Verify OPERATOR_KEY is a valid DER-encoded private key string

KEY_REQUIRED

Missing key in AccountCreateTransaction

Ensure you call .setECDSAKeyWithAlias(newPublicKey)

OPERATOR_ID and OPERATOR_KEY must be set

Environment variables not accessible

Check environment variables are set and accessible to your application

Cannot read properties of undefined

Missing imports or undefined variables

Verify all imports are included and variables are defined


What just happened?

  1. The SDK built an AccountCreateTransaction and signed it with your operator key.

  2. A consensus node validated the signature and charged the account creation fee.

  3. After network consensus, a unique account ID and EVM address were assigned and returned in the receipt.

  4. The account was funded with 20 HBAR from your operator account.

  5. The Mirror Node API confirmed your new account exists with the expected balance.


Next steps



🎉 Great work! You now control a brand new Hedera account secured by your fresh key pair. Keep the private key safe and never commit it to source control.

Have a question? Ask it on StackOverflow

Additional resources

Last updated

Was this helpful?