Skip to main content

hiero_sdk/topic/
topic_id.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use std::fmt::{
4    self,
5    Debug,
6    Display,
7    Formatter,
8};
9use std::str::FromStr;
10
11use hiero_sdk_proto::services;
12
13use crate::entity_id::{
14    Checksum,
15    ValidateChecksums,
16};
17use crate::{
18    Client,
19    EntityId,
20    Error,
21    FromProtobuf,
22    ToProtobuf,
23};
24
25/// The unique identifier for a topic on Hiero.
26#[derive(Hash, PartialEq, Eq, Clone, Copy)]
27#[repr(C)]
28pub struct TopicId {
29    /// A non-negative number identifying the shard containing this topic.
30    pub shard: u64,
31
32    /// A non-negative number identifying the realm within the shard containing this topic.
33    pub realm: u64,
34
35    /// A non-negative number identifying the entity within the realm containing this topic.
36    pub num: u64,
37
38    /// A checksum if the topic ID was read from a user inputted string which inclueded a checksum
39    pub checksum: Option<Checksum>,
40}
41
42impl TopicId {
43    /// Create a `TopicId` with the given `shard.realm.num`.
44    pub const fn new(shard: u64, realm: u64, num: u64) -> Self {
45        Self { shard, realm, num, checksum: None }
46    }
47
48    /// Create a new `TopicId` from protobuf-encoded `bytes`.
49    ///
50    /// # Errors
51    /// - [`Error::FromProtobuf`](crate::Error::FromProtobuf) if decoding the bytes fails to produce a valid protobuf.
52    /// - [`Error::FromProtobuf`](crate::Error::FromProtobuf) if decoding the protobuf fails.
53    pub fn from_bytes(bytes: &[u8]) -> crate::Result<Self> {
54        FromProtobuf::from_bytes(bytes)
55    }
56
57    /// Create a `TopicId` from a solidity address.
58    ///
59    /// # Errors
60    /// - [`Error::BasicParse`] if `address` cannot be parsed as a solidity address.
61    pub fn from_solidity_address(address: &str) -> crate::Result<Self> {
62        let EntityId { shard, realm, num, checksum } = EntityId::from_solidity_address(address)?;
63
64        Ok(Self { shard, realm, num, checksum })
65    }
66
67    /// Convert `self` to a protobuf-encoded [`Vec<u8>`].
68    #[must_use]
69    pub fn to_bytes(&self) -> Vec<u8> {
70        ToProtobuf::to_bytes(self)
71    }
72
73    /// Convert `self` into a solidity `address`
74    ///
75    /// # Errors
76    /// - [`Error::BasicParse`] if `self.shard` is larger than `u32::MAX`.
77    pub fn to_solidity_address(&self) -> crate::Result<String> {
78        EntityId { shard: self.shard, realm: self.realm, num: self.num, checksum: None }
79            .to_solidity_address()
80    }
81
82    /// Convert `self` to a string with a valid checksum.
83    #[must_use]
84    pub fn to_string_with_checksum(&self, client: &Client) -> String {
85        EntityId::to_string_with_checksum(self.to_string(), client)
86    }
87
88    /// Validates `self.checksum` (if it exists) for `client`.
89    ///
90    /// # Errors
91    /// - [`Error::BadEntityId`] if there is a checksum, and the checksum is not valid for the client's `ledger_id`.
92    pub fn validate_checksum(&self, client: &Client) -> crate::Result<()> {
93        EntityId::validate_checksum(self.shard, self.realm, self.num, self.checksum, client)
94    }
95}
96
97impl ValidateChecksums for TopicId {
98    fn validate_checksums(&self, ledger_id: &crate::ledger_id::RefLedgerId) -> Result<(), Error> {
99        EntityId::validate_checksum_for_ledger_id(
100            self.shard,
101            self.realm,
102            self.num,
103            self.checksum,
104            ledger_id,
105        )
106    }
107}
108
109impl Debug for TopicId {
110    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
111        write!(f, "\"{self}\"")
112    }
113}
114
115impl Display for TopicId {
116    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
117        write!(f, "{}.{}.{}", self.shard, self.realm, self.num)
118    }
119}
120
121impl FromProtobuf<services::TopicId> for TopicId {
122    fn from_protobuf(pb: services::TopicId) -> crate::Result<Self> {
123        Ok(Self {
124            num: pb.topic_num as u64,
125            shard: pb.shard_num as u64,
126            realm: pb.realm_num as u64,
127            checksum: None,
128        })
129    }
130}
131
132impl ToProtobuf for TopicId {
133    type Protobuf = services::TopicId;
134
135    fn to_protobuf(&self) -> Self::Protobuf {
136        services::TopicId {
137            topic_num: self.num as i64,
138            realm_num: self.realm as i64,
139            shard_num: self.shard as i64,
140        }
141    }
142}
143
144impl From<u64> for TopicId {
145    fn from(num: u64) -> Self {
146        Self { num, shard: 0, realm: 0, checksum: None }
147    }
148}
149
150impl FromStr for TopicId {
151    type Err = crate::Error;
152
153    fn from_str(s: &str) -> Result<Self, Self::Err> {
154        EntityId::from_str(s).map(Self::from)
155    }
156}
157
158impl From<EntityId> for TopicId {
159    fn from(value: EntityId) -> Self {
160        let EntityId { shard, realm, num, checksum } = value;
161
162        Self { shard, realm, num, checksum }
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use std::str::FromStr;
169
170    use expect_test::expect;
171
172    use crate::TopicId;
173
174    #[test]
175    fn parse() {
176        expect!["0.0.5005"].assert_eq(&TopicId::from_str("0.0.5005").unwrap().to_string());
177    }
178
179    #[test]
180    fn from_bytes() {
181        expect!["0.0.5005"].assert_eq(
182            &TopicId::from_bytes(&TopicId::new(0, 0, 5005).to_bytes()).unwrap().to_string(),
183        );
184    }
185
186    #[test]
187    fn from_solidity_address() {
188        expect!["0.0.5005"].assert_eq(
189            &TopicId::from_solidity_address("000000000000000000000000000000000000138D")
190                .unwrap()
191                .to_string(),
192        );
193    }
194
195    #[test]
196    fn to_solidity_address() {
197        expect!["000000000000000000000000000000000000138d"]
198            .assert_eq(&TopicId::new(0, 0, 5005).to_solidity_address().unwrap());
199    }
200}