How to Create Consensus Topics and Publish Messages to the Hedera Network Using Hedera Consensus Service (HCS)

How to Create Consensus Topics and Publish Messages to the Hedera Network Using Hedera Consensus Service (HCS)

A Step-by-Step Tutorial On Creating Consensus Topics Using Hedera Consensus Service (HCS) and the Hedera JavaScript SDK.

·

7 min read

Introduction

In this tutorial, we will create consensus topics and publish messages to the Hedera network using Hedera Consensus Service (HCS).

A brief introduction on Hedera: Hedera is an open-source public ledger that uses hashgraph consensus. Hedera is based on distributed ledger technology (DLT) like blockchain that utilizes a Directed Acyclic Graph (DAG) model. In contrast to blockchain technology, DAGs handle transaction validations by creating nodes concurrently. Whereas blockchain technology, miners can only create one block at a time and transaction validation is contingent upon those block creations. This is relevant to this tutorial because our consensus topic requests will be processed and published on the network faster than a typical blockchain.

What is Hedera Consensus Service (HCS)

The Hedera Consensus Service is a tool for creating immutable records on Hedera's public ledger using hashgraph consensus. The network is managed by participants distributed across multiple nodes. The transactions are stored in a cryptographic hash once it is validated on the network and logged. Each transaction is logged with a unique ID and timestamped event logs The logged events are immutable, meaning they can't be changed, to ensure accurate and tamper-proof transaction history. Some use cases for HCS include order tracking, voting, and audit logs.


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

  • Create a new consensus topic and publish messages to the network.

  • Fetch consensus topic and message information using Hashgraph's ** JavaScript SDK**.


The Tech Stack


Getting Started

**The prerequisites: **

  1. Install Git and Node.js on your machine.

Step 1: Set Up Node.js Environment

Open your IDE terminal and navigate to the directory where you want to create your Node.js project and run the following command:

// creates a new directory and change into that directory
mkdir hedera-hcs-tutorial && cd hedera-hcs-tutorial

In the same directory, initialize Node.js by running the following command:

npm init -y

Step 2: Install JavaScript SDK

In this step, we'll install the Hedera JavaScript SDK that will allow us to interact with the nodes on the Hedera network.

In the same terminal (root directory) run the following command:

npm install --save @hashgraph/sdk

Create a .env file where you will store your Hedera testnet account ID and private key.

Run the following command in your terminal to create the file:

touch .env

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

This is the dashboard where your account ID and private keys are:

hedera account ID private key dashboard.jpg

Now let's store your Hedera account ID and private key inside the .env file. Add the following lines of code into your .env file and replace the ACCOUNT_ID and PRIVATE_KEY variable values to reflect your Hedera account information:

File: ./.env

ACCOUNT_ID = ENTER YOUR ACCOUNT ID
PRIVATE_KEY = ENTER YOUR PRIVATE KEY

Install dotenv by running the following command in your terminal to import the modules into the project file later in Step 3:

npm install dotenv

Next, create an index.js file in the root directory of your project by running the following command in your terminal:

touch index.js

Step 3: Configure Client Connection

In this step, we'll set up a Client connection to interact with Hedera's network. The Client connection submits all transactions and queries to the network nodes. The transactions are sent as requests and they will be assigned a unique ID, timestamped, and logged into consensus order.

These are the modules we need to import from the SDK. Add the following lines of code at the top of your index.js file:

File: ./index.js

require("dotenv").config();
const {
    Client,
    TopicCreateTransaction,
    TopicMessageSubmitTransaction,
  } = require("@hashgraph/sdk");

We'll do most of our build inside of an async function.

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

The updated index.js file should look something like this:

File: ./index.js

// this import configures dotenv to access
// your account information stored in the `.env` file
require("dotenv").config();
// import modules needed from Hashgraph SDK
const {
    Client,
    TopicCreateTransaction,
    TopicMessageSubmitTransaction,
  } = require("@hashgraph/sdk");

async function main() {
    // create a client for the Hedera network
    const client = Client.forTestnet();
    // get the operator account ID and private key from `.env`
    const myAccountId = process.env.ACCOUNT_ID;
    const myPrivateKey = process.env.PRIVATE_KEY;
    // set the operator account ID and private key
    client.setOperator(myAccountId, myPrivateKey);
}
main();

Step 4: Create Consensus Service Topic

In this step, we will initialize the TopicCreateTransaction() constructor to implement methods that create new consensus topic transactions. These topics can be set to public or private. In order to submit messages to a private topic, you must set a topic key setSubmitKey() to sign with.

Consensus topics are like private messaging channels, similar to Discord. Discord: you join a server, agree to the terms (“sign") to gain access and roles (key) unlock private channels where only members with that role can send messages.

Initialize the ** TopicCreateTransaction()** constructor to create the topic transaction using the client connection we created in the previous step.

The updated index.js file should look something like this:

File: ./index.js

// this import configures dotenv to allow access to your
// account information stored in your `.env` file
require("dotenv").config();
const {
    Client,
    TopicCreateTransaction,
    TopicMessageSubmitTransaction,
  } = require("@hashgraph/sdk");

async function main() {
    // create a client for the Hedera network
    const client = Client.forTestnet();
    // get the account ID and private key from the environment
    const accountId = process.env.ACCOUNT_ID;
    const privateKey = process.env.PRIVATE_KEY;
    // set the operator account ID and private key
    client.setOperator(accountId, privateKey);

    const transactionId = await new TopicCreateTransaction();
    const txResponse = await transactionId.execute(client);
    const transactionReceipt = await txResponse.getReceipt(client);
    const newTopicId =  transactionReceipt.topicId;

    console.log("The new topic ID is " + newTopicId);

}
main();

Step 5: Submit Topic Message

In this final step, we will initialize the **TopicMessageSubmitTransaction() ** constructor and implement API methods provided by the SDK to publish messages to the topic.

Now we need to publish messages to the topic. Inside the for loop, we will set the top ID, message, and then execute the client to submit the message over the consensus service. The loop will iterate these steps until we have successfully sent five messages over the consensus service. Lastly, the receipt will be logged to the console to verify the transaction was successful.

The updated index.js file should look something like this:

File: ./index.js

require("dotenv").config();
const {
    Client,
    TopicCreateTransaction,
    TopicMessageSubmitTransaction,
  } = require("@hashgraph/sdk");

async function main() {
    // create a client for the Hedera network
    const client = Client.forTestnet();
    // get the account ID and private key from the environment
    const accountId = process.env.ACCOUNT_ID;
    const privateKey = process.env.PRIVATE_KEY;
    // set the operator account ID and private key
    client.setOperator(accountId, privateKey);

    const transactionId = await new TopicCreateTransaction();
    const txResponse = await transactionId.execute(client);
    const transactionReceipt = await txResponse.getReceipt(client);
    const newTopicId =  transactionReceipt.topicId;
    console.log("The new topic ID is " + newTopicId);

   for(var i = 0; i < 5; i++) {
        const hcsMessage = await new TopicMessageSubmitTransaction()
        .setTopicId(newTopicId)
        .setMessage("Hello, world!")
        .execute(client);

        console.log(`Message ${i}: 
        Status: SUCCESS 
            ${hcsMessage.toString()}`);
        }
}
main();

Run the following command in the project root directory to create a consensus topic and publish messages:

node index.js

Congrats on successfully creating a consensus topic and publishing your first messages! This is what your terminal should return:

HCS consensus topic transaction receipt

Check your transactions and topic ID on Hashscan explorer.


Next Steps

If you're up for a challenge:

  • Feel free to browse through the documentation and try implementing another functionality to this project you just created.

  • Try adding a subscribe functionality using the TopicMessageQuery() to receive all messages sent to a topic ID.


Additional Resources

Project reference code

Hedera Documentation

Check out my other articles


Where to Find Me

Happy building 🧱

Did you find this article valuable?

Support krystal by becoming a sponsor. Any amount is appreciated!