Hedera
Search…
Submit Your First Message

Summary

With the Hedera Consensus Service, you can develop applications like stock markets, audit logs, stable coins, or new network services that require high throughput and decentralized trust. This is made possible by having direct access to the native speed, security, and fair ordering guarantees of the hashgraph consensus algorithm, with the full trust of the Hedera ledger.
We recommend you complete the following introduction to get a basic understanding of Hedera transactions. This example does not build upon the previous examples.

1. Create your first topic

To create your first topic, you will use the TopicCreateTransaction(), set its properties, and submit it to the Hedera network. A public topic that anyone can submit messages to does not require any other properties to be set.
If you would like to create a private topic you can optionally set a topic key(setKey()) This means that messages submitted to this topic will require the topic key to sign the message submit transaction. If the topic key does not sign the message submit transaction, the message will not be submitted to the topic.
After submitting the transaction to the Hedera network, you can obtain the new token ID by requesting the receipt.
Java
JavaScript
Go
1
//Create a new topic
2
TransactionResponse txResponse = new TopicCreateTransaction()
3
.execute(client);
4
​
5
//Get the receipt
6
TransactionReceipt receipt = txResponse.getReceipt(client);
7
8
//Get the topic ID
9
TopicId topicId = receipt.topicId;
10
​
11
//Log the topic ID
12
System.out.println("Your topic ID is: " +topicId);
13
​
14
// Wait 5 seconds between consensus topic creation and subscription creation
15
Thread.sleep(5000);
Copied!
1
//Create a new topic
2
let txResponse = await new TopicCreateTransaction().execute(client);
3
​
4
//Get the receipt of the transaction
5
let receipt = await txResponse.getReceipt(client);
6
​
7
//Grab the new topic ID from the receipt
8
let topicId = receipt.topicId;
9
​
10
//Log the topic ID
11
console.log(`Your topic ID is: ${topicId}`);
12
​
13
// Wait 5 seconds between consensus topic creation and subscription
14
await new Promise((resolve) => setTimeout(resolve, 5000));
Copied!
1
//Create a new topic
2
transactionResponse, err := hedera.NewTopicCreateTransaction().
3
Execute(client)
4
​
5
if err != nil {
6
println(err.Error(), ": error creating topic")
7
return
8
}
9
​
10
//Get the topic create transaction receipt
11
transactionReceipt, err := transactionResponse.GetReceipt(client)
12
​
13
if err != nil {
14
println(err.Error(), ": error getting topic create receipt")
15
return
16
}
17
​
18
//Get the topic ID from the transaction receipt
19
topicID := *transactionReceipt.TopicID
20
​
21
//Log the topic ID to the console
22
fmt.Printf("topicID: %v\n", topicID)
Copied!

2. 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.
The Hedera testnet client already establishes a connection to a Hedera mirror node. You can set a custom mirror node by calling client.SetMirrorNetwork().
To subscribe to a topic you will use TopicMessageQuery(). You will provide it the topic ID to subscribe to, the Hedera mirror node client information, and the topic message contents to return.
Java
JavaScript
Go
1
//Subscribe to the topic
2
new TopicMessageQuery()
3
.setTopicId(topicId)
4
.subscribe(client, resp -> {
5
String messageAsString = new String(resp.contents, StandardCharsets.UTF_8);
6
System.out.println(resp.consensusTimestamp + " received topic message: " + messageAsString);
7
});
Copied!
1
//Create the query to subscribe to a topic
2
new TopicMessageQuery()
3
.setTopicId(topicId)
4
.subscribe(client, null, (message) => {
5
let messageAsString = Buffer.from(message.contents, "utf8").toString();
6
console.log(`${message.consensusTimestamp.toDate()} Received: ${messageAsString}`);
7
});
Copied!
1
//Create the query to subscribe to a topic
2
_, err = hedera.NewTopicMessageQuery().
3
SetTopicID(topicID).
4
Subscribe(client, func(message hedera.TopicMessage) {
5
fmt.Println(message.ConsensusTimestamp.String(), "received topic message ", string(message.Contents), "\r")
6
})
Copied!

3. 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 it.
Java
JavaScript
Go
1
//Submit a message to a topic
2
TransactionResponse submitMessage = new TopicMessageSubmitTransaction()
3
.setTopicId(topicId)
4
.setMessage("hello, HCS!")
5
.execute(client);
6
​
7
//Get the receipt of the transaction
8
TransactionReceipt receipt2 = submitMessage.getReceipt(client);
9
​
10
//Prevent the main thread from existing so the topic message can be returned and printed to the console
11
Thread.sleep(30000);
Copied!
1
// Send one message
2
let sendResponse = await new TopicMessageSubmitTransaction({
3
topicId: topicId,
4
message: "Hello, HCS!",
5
}).execute(client);
6
​
7
//Get the receipt of the transaction
8
const getReceipt = await sendResponse.getReceipt(client);
9
​
10
//Get the status of the transaction
11
const transactionStatus = getReceipt.status
12
console.log("The message transaction status" + transactionStatus)
Copied!
1
//Send "Hello, HCS!" to the topic
2
submitMessage, err := hedera.NewTopicMessageSubmitTransaction().
3
SetMessage([]byte("Hello, HCS!")).
4
SetTopicID(topicID).
5
Execute(client)
6
​
7
if err != nil {
8
println(err.Error(), ": error submitting to topic")
9
return
10
}
11
​
12
//Get the receipt of the transaction
13
receipt, err := submitMessage.GetReceipt(client)
14
​
15
//Get the transaction status
16
transactionStatus := receipt.Status
17
fmt.Println("The message transaction status " + transactionStatus.String())
18
​
19
//Prevent the program from exiting to display the message from the mirror to the console
20
time.Sleep(30000)
Copied!

Code Check βœ…

Java
JavaScript
Go
1
import com.hedera.hashgraph.sdk.*;
2
import io.github.cdimascio.dotenv.Dotenv;
3
​
4
import java.nio.charset.StandardCharsets;
5
import java.util.concurrent.TimeoutException;
6
​
7
public class CreateTopicTutorial {
8
public static void main(String[] args) throws TimeoutException, PrecheckStatusException, ReceiptStatusException, InterruptedException {
9
​
10
//Grab your Hedera testnet account ID and private key
11
AccountId myAccountId = AccountId.fromString(Dotenv.load().get("MY_ACCOUNT_ID"));
12
PrivateKey myPrivateKey = PrivateKey.fromString(Dotenv.load().get("MY_PRIVATE_KEY"));
13
​
14
//Build your Hedera client
15
Client client = Client.forTestnet();
16
client.setOperator(myAccountId, myPrivateKey);
17
​
18
//Create a new topic
19
TransactionResponse txResponse = new TopicCreateTransaction()
20
.execute(client);
21
​
22
//Get the receipt
23
TransactionReceipt receipt = txResponse.getReceipt(client);
24
​
25
//Get the topic ID
26
TopicId topicId = receipt.topicId;
27
​
28
//Log the topic ID
29
System.out.println("Your topic ID is: " +topicId);
30
​
31
// Wait 5 seconds between consensus topic creation and subscription creation
32
Thread.sleep(5000);
33
​
34
//Subscribe to the topic
35
new TopicMessageQuery()
36
.setTopicId(topicId)
37
.subscribe(client, resp -> {
38
String messageAsString = new String(resp.contents, StandardCharsets.UTF_8);
39
System.out.println(resp.consensusTimestamp + " received topic message: " + messageAsString);
40
});
41
​
42
//Submit a message to a topic
43
TransactionResponse submitMessage = new TopicMessageSubmitTransaction()
44
.setTopicId(topicId)
45
.setMessage("hello, HCS!")
46
.execute(client);
47
​
48
//Get the receipt of the transaction
49
TransactionReceipt receipt2 = submitMessage.getReceipt(client);
50
​
51
//Wait before the main thread exits to return the topic message to the console
52
Thread.sleep(30000);
53
​
54
}
55
}
Copied!
1
console.clear();
2
require("dotenv").config();
3
const {
4
AccountId,
5
PrivateKey,
6
Client,
7
TopicCreateTransaction,
8
TopicMessageQuery,
9
TopicMessageSubmitTransaction,
10
} = require("@hashgraph/sdk");
11
​
12
// Grab the OPERATOR_ID and OPERATOR_KEY from the .env file
13
const operatorId = AccountId.fromString(process.env.OPERATOR_ID);
14
const operatorKey = PrivateKey.fromString(process.env.OPERATOR_KEY);
15
​
16
// Build Hedera testnet and mirror node client
17
const client = Client.forTestnet();
18
​
19
// Set the operator account ID and operator private key
20
client.setOperator(operatorId, operatorKey);
21
​
22
async function main() {
23
//Create a new topic
24
let txResponse = await new TopicCreateTransaction().execute(client);
25
26
//Grab the newly generated topic ID
27
let receipt = await txResponse.getReceipt(client);
28
let topicId = receipt.topicId;
29
console.log(`Your topic ID is: ${topicId}`);
30
31
// Wait 5 seconds between consensus topic creation and subscription creation
32
await new Promise((resolve) => setTimeout(resolve, 5000));
33
34
//Create the query
35
new TopicMessageQuery().setTopicId(topicId).subscribe(client, null, (message) => {
36
let messageAsString = Buffer.from(message.contents, "utf8").toString();
37
console.log(`${message.consensusTimestamp.toDate()} Received: ${messageAsString}`);
38
});
39
40
// Send one message
41
let sendResponse = await new TopicMessageSubmitTransaction({
42
topicId: topicId,
43
message: "Hello, HCS!",
44
}).execute(client);
45
const getReceipt = await sendResponse.getReceipt(client);
46
47
//Get the status of the transaction
48
const transactionStatus = getReceipt.status
49
console.log("The message transaction status" + transactionStatus)
50
}
51
main();
Copied!
1
package main
2
​
3
import (
4
"fmt"
5
"os"
6
"time"
7
​
8
"github.com/hashgraph/hedera-sdk-go/v2"
9
"github.com/joho/godotenv"
10
)
11
​
12
func main() {
13
​
14
//Loads the .env file and throws an error if it cannot load the variables from that file corectly
15
err := godotenv.Load(".env")
16
if err != nil {
17
panic(fmt.Errorf("Unable to load enviroment variables from .env file. Error:\n%v\n", err))
18
}
19
​
20
//Grab your testnet account ID and private key from the .env file
21
myAccountId, err := hedera.AccountIDFromString(os.Getenv("MY_ACCOUNT_ID"))
22
if err != nil {
23
panic(err)
24
}
25
​
26
myPrivateKey, err := hedera.PrivateKeyFromString(os.Getenv("MY_PRIVATE_KEY"))
27
if err != nil {
28
panic(err)
29
}
30
​
31
//Create your testnet client
32
client := hedera.ClientForTestnet()
33
client.SetOperator(myAccountId, myPrivateKey)
34
​
35
//Create a new topic
36
transactionResponse, err := hedera.NewTopicCreateTransaction().
37
Execute(client)
38
​
39
if err != nil {
40
println(err.Error(), ": error creating topic")
41
return
42
}
43
​
44
//Get the topic create transaction receipt
45
transactionReceipt, err := transactionResponse.GetReceipt(client)
46
​
47
if err != nil {
48
println(err.Error(), ": error getting topic create receipt")
49
return
50
}
51
​
52
//Get the topic ID from the transaction receipt
53
topicID := *transactionReceipt.TopicID
54
​
55
//Log the topic ID to the console
56
fmt.Printf("topicID: %v\n", topicID)
57
​
58
//Create the query to subscribe to a topic
59
_, err = hedera.NewTopicMessageQuery().
60
SetTopicID(topicID).
61
Subscribe(client, func(message hedera.TopicMessage) {
62
fmt.Println(message.ConsensusTimestamp.String(), "received topic message ", string(message.Contents), "\r")
63
})
64
65
//Submit a message to the topic
66
submitMessage, err := hedera.NewTopicMessageSubmitTransaction().
67
SetMessage([]byte("Hello, HCS!")).
68
SetTopicID(topicID).
69
Execute(client)
70
​
71
if err != nil {
72
println(err.Error(), ": error submitting to topic")
73
return
74
}
75
76
//Get the transaction receipt
77
receipt, err := submitMessage.GetReceipt(client)
78
79
//Log the transaction status
80
transactionStatus := receipt.Status
81
fmt.Println("The transaction message status " + transactionStatus.String())
82
83
//Prevent the program from exiting to display the message from the mirror to the console
84
time.Sleep(30000)
Copied!