// Import the modules we need from the Hedera JavaScript SDK
const {
Client,
MirrorClient,
MirrorConsensusTopicQuery,
ConsensusTopicCreateTransaction,
ConsensusSubmitMessageTransaction
} = require("@hashgraph/sdk");
// Write our program in an asynchronous function
async function main() {
/* Get our environment variables (contained in a .env, or other way */
const operatorPrivateKey = process.env.OPERATOR_KEY;
const operatorAccount = process.env.OPERATOR_ID;
const mirrorNodeAddress = process.env.MIRROR_NODE_IP_ADDRESS;
const nodeAddress = process.env.NODE_ADDRESS;
// Create our Hedera Mainnet (or testnet) client
const client = Client.forTestnet();
client.setOperator(operatorAccount, operatorPrivateKey);
// Create our Mirror Node client
const consensusClient = new MirrorClient(mirrorNodeAddress);
// Build & execute our new Consensus Topic Create transaction
const createTopicTransactionId = await new ConsensusTopicCreateTransaction()
.setTopicMemo("Hello HCS Tutorial!")
.setMaxTransactionFee(1000000) // defaults to tinybars
.execute(client);
// Get the receipt of our transaction, to see if it was successful!
const createTopicReceipt = await createTopicTransactionId.getReceipt(client);
// If it was successful, it will contain a new topic ID!
const topicId = createTopicReceipt.getConsensusTopicId();
console.log(`topicId = ${topicId}`);
// Subscribe to a Hedera Mirror Node (or multiple!) to get pub-sub messaging over HCS
new MirrorConsensusTopicQuery()
.setTopicId(topicId)
.subscribe(
consensusClient,
(message) => console.log(message.toString()),
(error) => console.log(`Error: ${error}`)
);
// Build, specify topic ID, and send a new message to HCS
const newHCSMessage = await new ConsensusSubmitTransaction()
.setTopicId(newTopicId)
.setMessage("ℏello future!")
.execute(client);
// Get the receipt of our message to confirm it was successful
const hcsMessageReceipt = await newHCSMessage.getReceipt(client);
console.log('Message receipt: ' + hcsMessageReceipt);
}
main();