Applied Blockchain Center (ABC)
  • System requirements for ABC
  • Hedera
    • 🅰️About Hedera
    • 🖥️Environment Setup
    • Tutorials
      • Accounts
        • Get My Account Info
        • Get Other Account Info
        • Transfer HBAR
      • Consensus Service
        • Create Topic
        • Subscribe to a topic
        • Submit a message
      • File Service
        • Create a File
        • Retrieve File
      • Scheduled_TX
        • Create Scheduled Transaction
        • Scheduled Transaction Info
        • Delete Scheduled Transaction
        • Submit Signature
      • SmartContract Service
        • Deploy to Hedera
        • Seal Document
        • Get Seal
        • Check Seal Revocation Status
        • Revoke Document
      • Token Service
        • Fungible Token
        • Non-fungible Token
  • Hyperledger Fabric
    • 📑About Hyperledger Fabric
    • 💻Prerequisite Installation
    • Fabric Installation
      • 🧪Installation & Test
      • ✈️Launch Network
      • ⛓️Channel Creation
      • 🚚Chaincode Deployment
      • ▶️Chaincode Execution
  • Hyperledger Besu
    • Besu Network Set
Powered by GitBook
On this page
  • Step 1 : Imports
  • Step 2 : Environment Variables Retrieval
  • Step 3: Validation
  • Step 3 : Main Function

Was this helpful?

  1. Hedera
  2. Tutorials
  3. Consensus Service

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.

PreviousCreate TopicNextSubmit a message

Last updated 1 year ago

Was this helpful?