use hedera_proto::services;
use hedera_proto::services::crypto_service_client::CryptoServiceClient;
use time::Duration;
use tonic::transport::Channel;
use crate::protobuf::{
FromProtobuf,
ToProtobuf,
};
use crate::staked_id::StakedId;
use crate::transaction::{
AnyTransactionData,
ChunkInfo,
ToSchedulableTransactionDataProtobuf,
ToTransactionDataProtobuf,
TransactionData,
TransactionExecute,
};
use crate::{
AccountId,
BoxGrpcFuture,
Error,
Hbar,
Key,
LedgerId,
PublicKey,
Transaction,
ValidateChecksums,
};
pub type AccountCreateTransaction = Transaction<AccountCreateTransactionData>;
#[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 AccountCreateTransactionData {
key: Option<Key>,
initial_balance: Hbar,
receiver_signature_required: bool,
#[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>,
account_memo: String,
max_automatic_token_associations: u16,
alias: Option<PublicKey>,
evm_address: Option<[u8; 20]>,
#[cfg_attr(feature = "ffi", serde(flatten))]
staked_id: Option<StakedId>,
decline_staking_reward: bool,
}
impl Default for AccountCreateTransactionData {
fn default() -> Self {
Self {
key: None,
initial_balance: Hbar::ZERO,
receiver_signature_required: false,
auto_renew_period: Some(Duration::days(90)),
auto_renew_account_id: None,
account_memo: String::new(),
max_automatic_token_associations: 0,
alias: None,
evm_address: None,
staked_id: None,
decline_staking_reward: false,
}
}
}
impl AccountCreateTransaction {
#[must_use]
pub fn get_key(&self) -> Option<&Key> {
self.data().key.as_ref()
}
pub fn key(&mut self, key: impl Into<Key>) -> &mut Self {
self.data_mut().key = Some(key.into());
self
}
#[must_use]
pub fn get_initial_balance(&self) -> Hbar {
self.data().initial_balance
}
pub fn initial_balance(&mut self, balance: Hbar) -> &mut Self {
self.data_mut().initial_balance = balance;
self
}
#[must_use]
pub fn get_receiver_signature_required(&self) -> bool {
self.data().receiver_signature_required
}
pub fn receiver_signature_required(&mut self, required: bool) -> &mut Self {
self.data_mut().receiver_signature_required = required;
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
}
#[must_use]
pub fn get_account_memo(&self) -> &str {
&self.data().account_memo
}
pub fn account_memo(&mut self, memo: impl Into<String>) -> &mut Self {
self.data_mut().account_memo = memo.into();
self
}
#[must_use]
pub fn get_max_automatic_token_associations(&self) -> u16 {
self.data().max_automatic_token_associations
}
pub fn max_automatic_token_associations(&mut self, amount: u16) -> &mut Self {
self.data_mut().max_automatic_token_associations = amount;
self
}
#[must_use]
pub fn get_alias(&self) -> Option<&PublicKey> {
self.data().alias.as_ref()
}
pub fn alias(&mut self, key: PublicKey) -> &mut Self {
self.data_mut().alias = Some(key);
self
}
#[must_use]
pub fn get_evm_address(&self) -> Option<[u8; 20]> {
self.data().evm_address
}
pub fn evm_address(&mut self, evm_address: [u8; 20]) -> &mut Self {
self.data_mut().evm_address = Some(evm_address);
self
}
#[must_use]
pub fn get_staked_account_id(&self) -> Option<AccountId> {
self.data().staked_id.and_then(|it| it.to_account_id())
}
pub fn staked_account_id(&mut self, id: AccountId) -> &mut Self {
self.data_mut().staked_id = Some(StakedId::AccountId(id));
self
}
#[must_use]
pub fn get_staked_node_id(&self) -> Option<u64> {
self.data().staked_id.and_then(|it| it.to_node_id())
}
pub fn staked_node_id(&mut self, id: u64) -> &mut Self {
self.data_mut().staked_id = Some(StakedId::NodeId(id));
self
}
#[must_use]
pub fn get_decline_staking_reward(&self) -> bool {
self.data().decline_staking_reward
}
pub fn decline_staking_reward(&mut self, decline: bool) -> &mut Self {
self.data_mut().decline_staking_reward = decline;
self
}
}
impl TransactionData for AccountCreateTransactionData {}
impl TransactionExecute for AccountCreateTransactionData {
fn execute(
&self,
channel: Channel,
request: services::Transaction,
) -> BoxGrpcFuture<'_, services::TransactionResponse> {
Box::pin(async { CryptoServiceClient::new(channel).create_account(request).await })
}
}
impl ValidateChecksums for AccountCreateTransactionData {
fn validate_checksums(&self, ledger_id: &LedgerId) -> Result<(), Error> {
self.staked_id.validate_checksums(ledger_id)
}
}
impl ToTransactionDataProtobuf for AccountCreateTransactionData {
fn to_transaction_data_protobuf(
&self,
chunk_info: &ChunkInfo,
) -> services::transaction_body::Data {
let _ = chunk_info.assert_single_transaction();
services::transaction_body::Data::CryptoCreateAccount(self.to_protobuf())
}
}
impl ToSchedulableTransactionDataProtobuf for AccountCreateTransactionData {
fn to_schedulable_transaction_data_protobuf(
&self,
) -> services::schedulable_transaction_body::Data {
services::schedulable_transaction_body::Data::CryptoCreateAccount(self.to_protobuf())
}
}
impl From<AccountCreateTransactionData> for AnyTransactionData {
fn from(transaction: AccountCreateTransactionData) -> Self {
Self::AccountCreate(transaction)
}
}
impl FromProtobuf<services::CryptoCreateTransactionBody> for AccountCreateTransactionData {
fn from_protobuf(pb: services::CryptoCreateTransactionBody) -> crate::Result<Self> {
let evm_address = (!pb.evm_address.is_empty())
.then(|| pb.evm_address.as_slice().try_into())
.transpose()
.map_err(Error::basic_parse)?;
Ok(Self {
key: Option::from_protobuf(pb.key)?,
initial_balance: Hbar::from_tinybars(pb.initial_balance as i64),
receiver_signature_required: pb.receiver_sig_required,
auto_renew_period: pb.auto_renew_period.map(Into::into),
auto_renew_account_id: Option::from_protobuf(pb.auto_renew_account)?,
account_memo: pb.memo,
max_automatic_token_associations: pb.max_automatic_token_associations as u16,
alias: PublicKey::from_alias_bytes(&pb.alias)?,
evm_address,
staked_id: Option::from_protobuf(pb.staked_id)?,
decline_staking_reward: pb.decline_reward,
})
}
}
impl ToProtobuf for AccountCreateTransactionData {
type Protobuf = services::CryptoCreateTransactionBody;
fn to_protobuf(&self) -> Self::Protobuf {
let key = self.key.to_protobuf();
let auto_renew_period = self.auto_renew_period.to_protobuf();
let auto_renew_account = self.auto_renew_account_id.to_protobuf();
let staked_id = self.staked_id.map(|it| match it {
StakedId::NodeId(id) => {
services::crypto_create_transaction_body::StakedId::StakedNodeId(id as i64)
}
StakedId::AccountId(id) => {
services::crypto_create_transaction_body::StakedId::StakedAccountId(
id.to_protobuf(),
)
}
});
#[allow(deprecated)]
services::CryptoCreateTransactionBody {
key,
initial_balance: self.initial_balance.to_tinybars() as u64,
proxy_account_id: None,
send_record_threshold: i64::MAX as u64,
receive_record_threshold: i64::MAX as u64,
receiver_sig_required: self.receiver_signature_required,
auto_renew_period,
auto_renew_account,
shard_id: None,
realm_id: None,
new_realm_admin_key: None,
memo: self.account_memo.clone(),
max_automatic_token_associations: i32::from(self.max_automatic_token_associations),
alias: self.alias.map_or(vec![], |key| key.to_bytes_raw()),
evm_address: self.evm_address.map_or(vec![], Vec::from),
decline_reward: self.decline_staking_reward,
staked_id,
}
}
}
#[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::{
AccountCreateTransaction,
Hbar,
Key,
PublicKey,
};
const ACCOUNT_CREATE_EMPTY: &str = r#"{
"$type": "accountCreate"
}"#;
const ACCOUNT_CREATE_TRANSACTION_JSON: &str = r#"{
"$type": "accountCreate",
"key": {
"single": "302a300506032b6570032100d1ad76ed9b057a3d3f2ea2d03b41bcd79aeafd611f941924f0f6da528ab066fd"
},
"initialBalance": 1000,
"receiverSignatureRequired": true,
"autoRenewPeriod": 7776000,
"accountMemo": "An account memo",
"maxAutomaticTokenAssociations": 256,
"stakedNodeId": 7,
"declineStakingReward": false
}"#;
const KEY: &str =
"302a300506032b6570032100d1ad76ed9b057a3d3f2ea2d03b41bcd79aeafd611f941924f0f6da528ab066fd";
#[test]
#[ignore = "auto renew period is `None`"]
fn it_should_deserialize_empty() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(ACCOUNT_CREATE_EMPTY)?;
let data = assert_matches!(transaction.data(), AnyTransactionData::AccountCreate(transaction) => transaction);
assert_eq!(data.auto_renew_period, Some(Duration::days(90)));
Ok(())
}
#[test]
fn it_should_serialize() -> anyhow::Result<()> {
let mut transaction = AccountCreateTransaction::new();
transaction
.key(PublicKey::from_str(KEY)?)
.initial_balance(Hbar::from_tinybars(1000))
.receiver_signature_required(true)
.auto_renew_period(Duration::days(90))
.account_memo("An account memo")
.max_automatic_token_associations(256)
.staked_node_id(7)
.decline_staking_reward(false);
let transaction_json = serde_json::to_string_pretty(&transaction)?;
assert_eq!(transaction_json, ACCOUNT_CREATE_TRANSACTION_JSON);
Ok(())
}
#[test]
fn it_should_deserialize() -> anyhow::Result<()> {
let transaction: AnyTransaction =
serde_json::from_str(ACCOUNT_CREATE_TRANSACTION_JSON)?;
let data = assert_matches!(transaction.data(), AnyTransactionData::AccountCreate(transaction) => transaction);
assert_eq!(data.initial_balance.to_tinybars(), 1000);
assert_eq!(data.receiver_signature_required, true);
assert_eq!(data.auto_renew_period.unwrap(), Duration::days(90));
assert_eq!(data.account_memo, "An account memo");
assert_eq!(data.max_automatic_token_associations, 256);
assert_eq!(data.staked_id, Some(7.into()));
assert_eq!(data.decline_staking_reward, false);
let key = assert_matches!(data.key, Some(Key::Single(public_key)) => public_key);
assert_eq!(key, PublicKey::from_str(KEY)?);
Ok(())
}
}
}