-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathconsensus-pub-sub.js
More file actions
72 lines (59 loc) · 1.92 KB
/
consensus-pub-sub.js
File metadata and controls
72 lines (59 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const {
Client,
PrivateKey,
AccountId,
TopicMessageQuery,
TopicCreateTransaction,
TopicMessageSubmitTransaction,
} = require("@hashgraph/sdk");
async function main() {
let client;
if (process.env.HEDERA_NETWORK != null) {
switch (process.env.HEDERA_NETWORK) {
case "previewnet":
client = Client.forPreviewnet();
break;
default:
client = Client.forTestnet();
}
} else {
try {
client = await Client.fromConfigFile(process.env.CONFIG_FILE);
} catch (err) {
client = Client.forTestnet();
}
}
if (process.env.OPERATOR_KEY != null && process.env.OPERATOR_ID != null) {
const operatorKey = PrivateKey.fromString(process.env.OPERATOR_KEY);
const operatorId = AccountId.fromString(process.env.OPERATOR_ID);
client.setOperator(operatorId, operatorKey);
}
const response = await new TopicCreateTransaction()
.setTopicMemo("sdk example create_pub_sub.js")
.execute(client);
const receipt = await response.getReceipt(client);
const topicId = receipt.topicId;
console.log(`topicId = ${topicId}`);
new TopicMessageQuery()
.setTopicId(topicId)
.setStartTime(0)
.subscribe(
client,
(message) => console.log(Buffer.from(message.contents, "utf8").toString())
);
for (let i = 0; ; i += 1) {
// eslint-disable-next-line no-await-in-loop
await (await new TopicMessageSubmitTransaction()
.setTopicId(topicId)
.setMessage(`Hello, HCS! Message ${i}`)
.execute(client))
.getReceipt(client);
console.log(`Sent message ${i}`);
// eslint-disable-next-line no-await-in-loop
await sleep(2500);
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
main();