Create Topic

To create your first topic, you will use the TopicCreateTransaction(), set its properties, and submit it to the Hedera network. In this tutorial, you will create a public topic by not setting any properties on the topic. This means that anyone can send messages to your topic.

Step 1 : Imports

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

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

const {
    TopicCreateTransaction,
    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 and MY_PRIVATE_KEY from the .env file using process.env.

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

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 4 :Main Function

  • 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 TopicCreateTransaction object to create a new topic on the Hedera network.

  • The transaction is executed, and the resulting transaction response (txResponse) is obtained.

  • The receipt of the transaction is retrieved, and the new topic ID is extracted from it.

  • The topic ID is logged to the console.

  • There's a 5-second delay added using setTimeout() before exiting the process.

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 a new topic
    let txResponse = await new TopicCreateTransaction().execute(client);

    // Get the receipt of the transaction
    let receipt = await txResponse.getReceipt(client);

    // Grab the new topic ID from the receipt
    let topicId = receipt.topicId;

    // Log the topic ID
    console.log(`Your topic ID is: ${topicId}`);

    // Wait 5 seconds between consensus topic creation and subscription
    await new Promise((resolve) => setTimeout(resolve, 5000));

    process.exit(); // Exit the process
}

Step 5 : Execution

This line calls the main() function to start the execution of the script.

main();

This script creates a new consensus topic on the Hedera network and logs the topic ID to the console.

Last updated