Subscribe to a topic

After you create the topic, you will want to subscribe to the topic via a Hedera mirror node. Subscribing to a topic via a Hedera mirror node allows you to receive the stream of messages that are being submitted to it.

Step 1 : Imports

  • The script imports necessary modules from the Hedera JavaScript SDK: TopicMessageQuery, Client, and PrivateKey.

  • It also imports the dotenv module to load environment variables from a .env file located in the Consensus_Service directory.

const {
    TopicMessageQuery,
    Client,
    PrivateKey
} = require("@hashgraph/sdk");
require('dotenv').config({ path: 'Consensus_Service/.env' });

Step 2 : Environment Variables Retrieval

These lines retrieve environment variables such as MY_ACCOUNT_ID, MY_PRIVATE_KEY, and TOPIC_ID from the .env file using process.env.

const myAccountId = process.env.MY_ACCOUNT_ID;
const myPrivateKey = PrivateKey.fromString(process.env.MY_PRIVATE_KEY);
const topicId = process.env.TOPIC_ID;

Step 3: Validation

This block of code ensures that the required environment variables (MY_ACCOUNT_ID and MY_PRIVATE_KEY) are present. If not, it throws an error.

if (myAccountId == null ||
    myPrivateKey == null ) {
    throw new Error("Environment variables myAccountId and myPrivateKey must be present");
}

Step 3 : Main Function

  • This is the main function named main().

  • It creates a client instance for the Hedera testnet and sets the operator account using the user's account ID and private key.

  • It creates a new TopicMessageQuery object to subscribe to a topic.

  • The topic ID and start time are set using the retrieved environment variables.

  • The script subscribes to the topic using the subscribe() method. Incoming messages are logged to the console.

async function main() {
    const client = Client.forTestnet(); // Create a client for the Hedera testnet
    client.setOperator(myAccountId, myPrivateKey); // Set the operator account for the client

    // Create the query to subscribe to a topic
    new TopicMessageQuery()
        .setTopicId(topicId) // Set the topic ID to subscribe to
        .setStartTime(0) // Set the start time of the subscription
        .subscribe( // Subscribe to the topic
            client,
            (message) => console.log(Buffer.from(message.contents, "utf8").toString()) // Log incoming messages to the console
        );
}

main();

This script subscribes to a consensus topic on the Hedera network and listens for incoming messages. When a message is received, it is logged to the console.

Last updated