Submit a message
Now you are ready to submit your first message to the topic. To do this, you will use TopicMessageSubmitTransaction(). For this transaction, you will provide the topic ID and the message to submit to
Step 1 : Imports
- The script imports necessary modules from the Hedera JavaScript SDK: - PrivateKey,- TopicMessageSubmitTransaction, and- Client.
- It also imports the - dotenvmodule to load environment variables from a- .envfile located in the- Consensus_Servicedirectory.
const {
    PrivateKey,
    TopicMessageSubmitTransaction,
    Client
} = 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 4 : 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 - TopicMessageSubmitTransactionobject to submit a message to a topic.
- The topic ID and message content are set using the retrieved environment variables. 
- The transaction is executed using the - execute()method, and the resulting transaction response (- sendResponse) is obtained.
- The receipt of the transaction is retrieved using - getReceipt().
- The status of the transaction is extracted from the receipt and 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
    // Send one message to the specified topic
    let sendResponse = await new TopicMessageSubmitTransaction({
        topicId: topicId, // Set the topic ID
        message: "This is a very first message to my new topic!", // Set the message content
    }).execute(client);
    // Get the receipt of the transaction
    const getReceipt = await sendResponse.getReceipt(client);
    // Get the status of the transaction
    const transactionStatus = getReceipt.status;
    console.log("The message transaction status: " + transactionStatus);
    process.exit(); // Exit the process
}
main();
This script submits a message to a consensus topic on the Hedera network and logs the transaction status to the console.
Last updated
Was this helpful?