use hedera_proto::services;
use hedera_proto::services::consensus_service_client::ConsensusServiceClient;
use time::Duration;
use tonic::transport::Channel;
use crate::protobuf::{
FromProtobuf,
ToProtobuf,
};
use crate::transaction::{
AnyTransactionData,
ChunkInfo,
ToSchedulableTransactionDataProtobuf,
ToTransactionDataProtobuf,
TransactionData,
TransactionExecute,
};
use crate::{
AccountId,
BoxGrpcFuture,
Error,
Key,
LedgerId,
Transaction,
ValidateChecksums,
};
pub type TopicCreateTransaction = Transaction<TopicCreateTransactionData>;
#[cfg_attr(feature = "ffi", serde_with::skip_serializing_none)]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "ffi", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "ffi", serde(default, rename_all = "camelCase"))]
pub struct TopicCreateTransactionData {
#[cfg_attr(feature = "ffi", serde(skip_serializing_if = "String::is_empty"))]
topic_memo: String,
admin_key: Option<Key>,
submit_key: Option<Key>,
#[cfg_attr(
feature = "ffi",
serde(with = "serde_with::As::<Option<serde_with::DurationSeconds<i64>>>")
)]
auto_renew_period: Option<Duration>,
auto_renew_account_id: Option<AccountId>,
}
impl Default for TopicCreateTransactionData {
fn default() -> Self {
Self {
topic_memo: String::new(),
admin_key: None,
submit_key: None,
auto_renew_period: Some(Duration::days(90)),
auto_renew_account_id: None,
}
}
}
impl TopicCreateTransaction {
#[must_use]
pub fn get_topic_memo(&self) -> &str {
&self.data().topic_memo
}
pub fn topic_memo(&mut self, memo: impl Into<String>) -> &mut Self {
self.data_mut().topic_memo = memo.into();
self
}
#[must_use]
pub fn get_admin_key(&self) -> Option<&Key> {
self.data().admin_key.as_ref()
}
pub fn admin_key(&mut self, key: impl Into<Key>) -> &mut Self {
self.data_mut().admin_key = Some(key.into());
self
}
#[must_use]
pub fn get_submit_key(&self) -> Option<&Key> {
self.data().submit_key.as_ref()
}
pub fn submit_key(&mut self, key: impl Into<Key>) -> &mut Self {
self.data_mut().submit_key = Some(key.into());
self
}
#[must_use]
pub fn get_auto_renew_period(&self) -> Option<Duration> {
self.data().auto_renew_period
}
pub fn auto_renew_period(&mut self, period: Duration) -> &mut Self {
self.data_mut().auto_renew_period = Some(period);
self
}
#[must_use]
pub fn get_auto_renew_account_id(&self) -> Option<AccountId> {
self.data().auto_renew_account_id
}
pub fn auto_renew_account_id(&mut self, id: AccountId) -> &mut Self {
self.data_mut().auto_renew_account_id = Some(id);
self
}
}
impl TransactionData for TopicCreateTransactionData {}
impl TransactionExecute for TopicCreateTransactionData {
fn execute(
&self,
channel: Channel,
request: services::Transaction,
) -> BoxGrpcFuture<'_, services::TransactionResponse> {
Box::pin(async { ConsensusServiceClient::new(channel).create_topic(request).await })
}
}
impl ValidateChecksums for TopicCreateTransactionData {
fn validate_checksums(&self, ledger_id: &LedgerId) -> Result<(), Error> {
self.auto_renew_account_id.validate_checksums(ledger_id)
}
}
impl ToTransactionDataProtobuf for TopicCreateTransactionData {
fn to_transaction_data_protobuf(
&self,
chunk_info: &ChunkInfo,
) -> services::transaction_body::Data {
let _ = chunk_info.assert_single_transaction();
services::transaction_body::Data::ConsensusCreateTopic(self.to_protobuf())
}
}
impl ToSchedulableTransactionDataProtobuf for TopicCreateTransactionData {
fn to_schedulable_transaction_data_protobuf(
&self,
) -> services::schedulable_transaction_body::Data {
services::schedulable_transaction_body::Data::ConsensusCreateTopic(self.to_protobuf())
}
}
impl From<TopicCreateTransactionData> for AnyTransactionData {
fn from(transaction: TopicCreateTransactionData) -> Self {
Self::TopicCreate(transaction)
}
}
impl FromProtobuf<services::ConsensusCreateTopicTransactionBody> for TopicCreateTransactionData {
fn from_protobuf(pb: services::ConsensusCreateTopicTransactionBody) -> crate::Result<Self> {
Ok(Self {
topic_memo: pb.memo,
admin_key: Option::from_protobuf(pb.admin_key)?,
submit_key: Option::from_protobuf(pb.submit_key)?,
auto_renew_period: pb.auto_renew_period.map(Into::into),
auto_renew_account_id: Option::from_protobuf(pb.auto_renew_account)?,
})
}
}
impl ToProtobuf for TopicCreateTransactionData {
type Protobuf = services::ConsensusCreateTopicTransactionBody;
fn to_protobuf(&self) -> Self::Protobuf {
services::ConsensusCreateTopicTransactionBody {
auto_renew_account: self.auto_renew_account_id.to_protobuf(),
memo: self.topic_memo.clone(),
admin_key: self.admin_key.to_protobuf(),
submit_key: self.submit_key.to_protobuf(),
auto_renew_period: self.auto_renew_period.to_protobuf(),
}
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "ffi")]
mod ffi {
use std::str::FromStr;
use assert_matches::assert_matches;
use time::Duration;
use crate::transaction::{
AnyTransaction,
AnyTransactionData,
};
use crate::{
AccountId,
Key,
PublicKey,
TopicCreateTransaction,
};
const TOPIC_CREATE_EMPTY: &str = r#"{
"$type": "topicCreate"
}"#;
const TOPIC_CREATE_TRANSACTION_JSON: &str = r#"{
"$type": "topicCreate",
"topicMemo": "A topic memo",
"adminKey": {
"single": "302a300506032b6570032100d1ad76ed9b057a3d3f2ea2d03b41bcd79aeafd611f941924f0f6da528ab066fd"
},
"submitKey": {
"single": "302a300506032b6570032100b5b4d9351ebdf266ef3989aed4fd8f0cfcf24b75ba3d0df19cd3946771b40500"
},
"autoRenewPeriod": 7776000,
"autoRenewAccountId": "0.0.1001"
}"#;
const ADMIN_KEY: &str =
"302a300506032b6570032100d1ad76ed9b057a3d3f2ea2d03b41bcd79aeafd611f941924f0f6da528ab066fd";
const SUBMIT_KEY: &str =
"302a300506032b6570032100b5b4d9351ebdf266ef3989aed4fd8f0cfcf24b75ba3d0df19cd3946771b40500";
#[test]
fn it_should_serialize() -> anyhow::Result<()> {
let mut transaction = TopicCreateTransaction::new();
transaction
.topic_memo("A topic memo")
.admin_key(PublicKey::from_str(ADMIN_KEY)?)
.submit_key(PublicKey::from_str(SUBMIT_KEY)?)
.auto_renew_period(Duration::days(90))
.auto_renew_account_id(AccountId::from(1001));
let transaction_json = serde_json::to_string_pretty(&transaction)?;
assert_eq!(transaction_json, TOPIC_CREATE_TRANSACTION_JSON);
Ok(())
}
#[test]
fn it_should_deserialize() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(TOPIC_CREATE_TRANSACTION_JSON)?;
let data = assert_matches!(transaction.into_body().data, AnyTransactionData::TopicCreate(transaction) => transaction);
assert_eq!(data.topic_memo, "A topic memo");
assert_eq!(data.auto_renew_period.unwrap(), Duration::days(90));
let admin_key =
assert_matches!(data.admin_key.unwrap(), Key::Single(public_key) => public_key);
assert_eq!(admin_key, PublicKey::from_str(ADMIN_KEY)?);
let submit_key =
assert_matches!(data.submit_key.unwrap(), Key::Single(public_key) => public_key);
assert_eq!(submit_key, PublicKey::from_str(SUBMIT_KEY)?);
assert_eq!(data.auto_renew_account_id, Some(AccountId::from(1001)));
Ok(())
}
#[test]
#[ignore = "auto renew period is `None`"]
fn it_should_deserialize_empty() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(TOPIC_CREATE_EMPTY)?;
let data = assert_matches!(transaction.data(), AnyTransactionData::TopicCreate(transaction) => transaction);
assert_eq!(data.auto_renew_period.unwrap(), Duration::days(90));
Ok(())
}
}
}