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 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 Custodians Library
      • How to use it
    • 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 Creating a Topic
  • Prerequisites
  • Step 1: Navigate to the hcs example in the project directory
  • Step 2: Guided Code Walkthrough
  • Create a Hedera Testnet Client
  • Create a Topic Create Transaction
  • Publish a Message to the New Topic
  • Query the Topic Data from the Mirror Node API
  • Step 3: Run and Verify Topic on HashScan
  • Code Check ✅
  • Complete
  • Next Steps

Was this helpful?

Edit on GitHub
  1. Getting Started
  2. Web2 Developers

Create a Topic

PreviousCreate a TokenNextEVM Developers

Last updated 1 month ago

Was this helpful?

Introduction to Creating a Topic

This tutorial will walk you through a TopicCreateTransaction to create a new consensus topic and a TopicMessageSubmitTransaction to publish your first message using the . The service provides developers a decentralized tool for logging, ordering, and timestamping messages or transactions on the Hedera network.

What you will accomplish

By the end of this tutorial, you will be able to:

  • Create new consensus topics using HCS.

  • Publish your first message using HCS.

  • 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 hcs example in the project directory

From the root directory of the hedera-future-world-language project CD (change directories) to the topic create transaction example.

cd hcs

If you completed a previous example in the series you can use to go back to the root directory and cd into this example.

cd ../hcs

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

script-hcs-topic.js
import {
    Client,
    PrivateKey,
    AccountId,
    TokenCreateTransaction,
    TokenType,
} from '@hashgraph/sdk';
import dotenv from 'dotenv';
import {
    createLogger,
} from '../util/util.js';

const logger = await createLogger({
    scriptId: 'htsFt',
    scriptCategory: 'task',
});
let client;

async function scriptHtsFungibleToken() {
    logger.logStart('Hello Future World - HTS Fungible Token - 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 OPERATOR_ACCOUNT_ID and OPERATOR_ACCOUNT_PRIVATE_KEY environment variables');
    }
    const operatorId = AccountId.fromString(operatorIdStr);
    const operatorKey = PrivateKey.fromStringECDSA(operatorKeyStr);
    client = Client.forTestnet().setOperator(operatorId, operatorKey);
    logger.log('Using account:', operatorIdStr);
}
ScriptHcsTopic.java
package hcs;

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
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 ScriptHcsTopic {
    public static void main(String[] args) throws Exception {
        System.out.println("🏁 Hello Future World - HCS Topic - 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);
        System.out.println("Using account: " + operatorIdStr);
}
script-hcs-topic.go
package main

import (
	"encoding/json"
	"encoding/base64"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

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

type TopicMessagesMNAPIResponse struct {
	Messages []struct {
		SequenceNumber int64 `json:"sequence_number"`
		Message string `json:"message"`
	} `json:"messages"`
}

func main() {
	fmt.Println("🏁 Hello Future World - HCS Topic - 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.

script-hcs-topic.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));

Client client = Client.forTestnet().setOperator(operatorId, operatorKey);

//Set the default maximum transaction fee (in HBAR)
client.setDefaultMaxTransactionFee(new Hbar(100));
        
//Set the default maximum payment for queries (in HBAR)
client.setDefaultMaxQueryPayment(new Hbar(50));
script-hcs-topic.go
// The client operator ID and key is the account that will be automatically set to pay for the transaction fees for each transaction
client := hedera.ClientForTestnet()
client.SetOperator(operatorId, operatorKey)

// Set the default maximum transaction fee (in HBAR)
client.SetDefaultMaxTransactionFee(hedera.HbarFrom(100, hedera.HbarUnits.Hbar))
	
// Set the default maximum payment for queries (in HBAR)
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 Topic Create Transaction

After the transaction is completed, you'll need to extract the topicID from the transaction receipt, as it's required for submitting messages to the topic. This step has already been completed for you, no further modification is necessary.

script-hcs-topic.js
// Create a new HCS topic
const topicCreateTx = await new TopicCreateTransaction()
    .setTopicMemo(`Hello Future World topic - ${logger.version}`)
    // Freeze the transaction to prepare for signing
    .freezeWith(client);

// Get the transaction ID of the transaction.
// The SDK automatically generates and assigns a transaction ID when the transaction is created
const topicCreateTxId = topicCreateTx.transactionId;
logger.log("The topic create transaction ID: ", topicCreateTxId.toString());

// Sign the transaction with the account key that will be paying for this transaction
const topicCreateTxSigned = await topicCreateTx.sign(operatorKey);

// Submit the transaction to the Hedera Testnet
const topicCreateTxSubmitted = await topicCreateTxSigned.execute(client);

// Get the transaction receipt
const topicCreateTxReceipt = await topicCreateTxSubmitted.getReceipt(client);

// Get the topic ID
const topicId = topicCreateTxReceipt.topicId;
logger.log('topicId:', topicId.toString());
ScriptHcsTopic.java
// Create a Hedera Consensus Service (HCS) topic
TopicCreateTransaction topicCreateTx = new TopicCreateTransaction()
     .setTopicMemo("Hello Future World topic - xyz")
     // Freeze the transaction to prepare for signing
     .freezeWith(client);

// Get the transaction ID of the transaction.
// The SDK automatically generates and assigns a transaction ID when the transaction is created
TransactionId topicCreateTxId = topicCreateTx.getTransactionId();
System.out.println("The topic create transaction ID: " + topicCreateTxId.toString());

// Sign the transaction with the account key that will be paying for this transaction
TopicCreateTransaction topicCreateTxSigned = topicCreateTx.sign(operatorKey);

// Submit the transaction to the Hedera Testnet
TransactionResponse topicCreateTxSubmitted = topicCreateTxSigned.execute(client);

// Get the transaction receipt
TransactionReceipt topicCreateTxReceipt = topicCreateTxSubmitted.getReceipt(client);

// Get the topic ID
TopicId topicId = topicCreateTxReceipt.topicId;
System.out.println("Topic ID:" + topicId.toString());
script-hcs-topic.go
// Create a Hedera Consensus Service (HCS) topic
topicCreateTx, _ := hedera.NewTopicCreateTransaction().
SetTopicMemo("Hello Future World topic - xyz").
// Freeze the transaction to prepare for signing
FreezeWith(client);

// Get the transaction ID of the transaction.
// The SDK automatically generates and assigns a transaction ID when the transaction is created
topicCreateTxId := topicCreateTx.GetTransactionID();
fmt.Printf("The topic create transaction ID: %s\n", topicCreateTxId.String())

// Sign the transaction with the private key of the treasury account (operator key)
topicCreateTxSigned := topicCreateTx.Sign(operatorKey)

// Submit the transaction to the Hedera Testnet
topicCreateTxSubmitted, _ := topicCreateTxSigned.Execute(client)

// Get the transaction receipt
topicCreateTxReceipt, _ := topicCreateTxSubmitted.GetReceipt(client)

// Get the token ID
topicId := topicCreateTxReceipt.TopicID
fmt.Printf("Topic ID: %s\n", topicId.String())

Publish a Message to the New Topic

script-hcs-topic.js
// Publish a message to the HCS topic
const topicMsgSubmitTx = await new TopicMessageSubmitTransaction()
    //Set the transaction memo with the hello future world ID
    .setTransactionMemo(`Hello Future World topic message - ${logger.version}`)
    .setTopicId(topicId)
    //Set the topic message contents
    .setMessage('Hello HCS!')
    // Freeze the transaction to prepare for signing
    .freezeWith(client);

// Get the transaction ID of the transaction. The SDK automatically generates and assigns a transaction ID when the transaction is created
const topicMsgSubmitTxId = topicMsgSubmitTx.transactionId;
logger.log('The message submit create transaction ID: ',
    topicMsgSubmitTxId.toString());

// Sign the transaction with the account key that will be paying for this transaction
const topicMsgSubmitTxSigned = await topicMsgSubmitTx.sign(operatorKey);

// Submit the transaction to the Hedera Testnet
const topicMsgSubmitTxSubmitted = await topicMsgSubmitTxSigned.execute(client);

// Get the transaction receipt
const topicMsgSubmitTxReceipt = await topicMsgSubmitTxSubmitted.getReceipt(client);

// Get the topic message sequence number
const topicMsgSeqNum = topicMsgSubmitTxReceipt.topicSequenceNumber;
logger.log('topicMsgSeqNum:', topicMsgSeqNum.toString());
ScriptHcsTopic.java
   // Publish a message to the Hedera Consensus Service (HCS) topic
        System.out.println("🟣 Publish message to HCS topic");
        TopicMessageSubmitTransaction topicMsgSubmitTx = new TopicMessageSubmitTransaction()
            //Set the transaction memo with the hello future world ID
            .setTransactionMemo("Hello Future World topic message - xyz")
            .setTopicId(topicId)
            //Set the topic message contents
            .setMessage("Hello HCS!")
            // Freeze the transaction to prepare for signing
            .freezeWith(client);

        // Get the transaction ID of the transaction.
        // The SDK automatically generates and assigns a transaction ID when the transaction is created
        TransactionId topicMsgSubmitTxId = topicMsgSubmitTx.getTransactionId();
        System.out.println(
            "The topic message submit transaction ID: " +
            topicMsgSubmitTxId.toString()
        );

        // Sign the transaction with the account key that will be paying for this transaction
        TopicMessageSubmitTransaction topicMsgSubmitTxSigned = topicMsgSubmitTx.sign(operatorKey);

        // Submit the transaction to the Hedera Testnet
        TransactionResponse topicMsgSubmitTxSubmitted =
            topicMsgSubmitTxSigned.execute(client);

        // Get the transaction receipt
        TransactionReceipt topicMsgSubmitTxReceipt =
            topicMsgSubmitTxSubmitted.getReceipt(client);

        // Get the topic message sequence number
        Long topicMsgSeqNum = topicMsgSubmitTxReceipt.topicSequenceNumber;
        System.out.println("Topic Message Sequence Number:" + topicMsgSeqNum.toString());
script-hcs-topic.go
// Publish a message to the Hedera Consensus Service (HCS) topic
topicMsgSubmitTx, _ := hedera.NewTopicMessageSubmitTransaction().
//Set the transaction memo with the hello future world ID
SetTransactionMemo("Hello Future World topic message - xyz").
SetTopicID(*topicId).
// Set the topic message contents
SetMessage([]byte("Hello HCS!")).
// Freeze the transaction to prepare for signing
FreezeWith(client);

// Get the transaction ID of the transaction.
// The SDK automatically generates and assigns a transaction ID when the transaction is created
topicMsgSubmitTxId := topicMsgSubmitTx.GetTransactionID();
fmt.Printf("The topic message submit transaction ID: %s\n", topicMsgSubmitTxId.String())

// Sign the transaction with the private key of the treasury account (operator key)
topicMsgSubmitTxSigned := topicMsgSubmitTx.Sign(operatorKey)

// Submit the transaction to the Hedera Testnet
topicMsgSubmitTxSubmitted, _ := topicMsgSubmitTxSigned.Execute(client)

// Get the transaction receipt
topicMsgSubmitTxReceipt, _ := topicMsgSubmitTxSubmitted.GetReceipt(client)

// Get the topic message sequence number
topicMsgSeqNum := topicMsgSubmitTxReceipt.TopicSequenceNumber
fmt.Printf("Topic Message Sequence Number: %v\n", topicMsgSeqNum)

Query the Topic Data from the Mirror Node API

To query the specified topic ID and verify the messages within the topic, you will want to use the Mirror Node API with the path /api/v1/topics/{topicId}/messages for this task.

  • Specify topicId within the URL path

  • Specify base64 as the encoding query parameter

  • Specify 5 as the limit query parameter

  • Specify asc as the order query parameter

  • Specify 1 as the sequencenumber query parameter

The constructed topicVerifyMirrorNodeApiUrl should look like this:

script-hcs-topic.js
const topicVerifyMirrorNodeApiUrl =
    `https://testnet.mirrornode.hedera.com/api/v1/topics/${topicId.toString()}/
    messages?encoding=base64&limit=5&order=asc&sequencenumber=1`;
Learn more about Mirror Node APIs

You can perform the same Mirror Node API query as topicVerifyMirrorNodeApiUrl above. This is what the relevant part of the Swagger page would look like when doing so:


Step 3: Run and Verify Topic on HashScan

In the terminal, cd into the hcs directory and run the topic create transaction script:

node script-hcs-topic.js
gradle run
go mod tidy
go run script-hcs-topic.go

Sample output:

🏁 Hello Future World - HCS Topic - start
Using account: 0.0.1455
Using operatorKey: 1a83c7c0fe90a1d24b8f5bcd3b074aecad834d7a9fbe130ea133eb4e01775300
🟣 Creating new HCS topic
The topic create transaction ID: 0.0.1455@1732734923.966673221
Topic ID: 0.0.5181441
🟣 Publish message to HCS topic
The topic message submit transaction ID: 0.0.1455@1732734922.264842548
Topic Message Sequence Number: 1
🟣 View the topic on HashScan
Topic Hashscan URL: https://hashscan.io/testnet/topic/0.0.5181441
🟣 Get topic data from the Hedera Mirror Node
The token Hedera Mirror Node API URL: https://testnet.mirrornode.hedera.com/api/v1/topics/0.0.5181441/messages?encoding=base64&limit=5&order=asc&sequencenumber=1
Messages retrieved from this topic:
#1: Hello HCS!
🎉 Hello Future World - HCS Topic - complete

To verify that both the TopicCreateTransaction and TopicMessageSubmitTransaction have been successful, check the transaction details on HashScan. Open View the topic on HashScan URL from the console output in your browser and check that:

  • The topic exists, and its topic ID matches topicId output by the script. (1)

  • There is one entry in the topic, and its message is Hello HCS - followed by your name/ nickname. (2)


Code Check ✅


Complete

Congratulations, you have completed the Create a Topic 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 HCS create a topic script (e.g., /hcs/script-hcs-topic.js) in a code editor llike , , 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 topic while the dotenv package loads environment variables from the .env file, such as the operator account ID, private key, and name variables.

To create your first topic, you will use the TopicCreateTransaction(), set its properties, and submit it to the Hedera network. In this guide, you will create a public topic by not setting any properties on the topic. This means that anyone can send messages to your topic. Refer to the transaction and query for the full list of base transaction fees.

Now you are ready to submit your first message to the topic. You will use the TopicMessageSubmitTransaction() class to submit your first message to the topic. This involves setting the topicId and the message content, signing the transaction, and submitting it to the Hedera network. Messages can be any data up to 1024 bytes, and each message costs to send. This means you can send 10,000 messages for just $1 on the Hedera network. For the message content, use a string in the format "Hello HCS!".

The total cost to create a topic and send a message to it is approximately , making it an affordable way to interact with the Hedera network.

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

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

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

VS Code
IntelliJ
Gitpod
fees table
$0.0001
Hedera Testnet Mirror Node REST API
REST API
Java
JavaScript
Go
Hedera Discord
developer-general
Stack Overflow
here

Transfer HBAR

Learn how to transfer HBAR, Hedera's native cryptocurrency, between accounts.

Create a Token

Create and Fund Your Hedera Testnet Account
Environment Setup

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

LEARN MORE
LEARN MORE
$0.0101
Hedera Consensus Service (HCS)
Hedera Token Service
LogoFees | Hedera
HCS topic in Hashscan, with annotated items to check.