use async_trait::async_trait;
use hedera_proto::services;
use hedera_proto::services::token_service_client::TokenServiceClient;
use time::{
Duration,
OffsetDateTime,
};
use tonic::transport::Channel;
use crate::entity_id::AutoValidateChecksum;
use crate::protobuf::ToProtobuf;
use crate::token::custom_fees::AnyCustomFee;
use crate::token::token_supply_type::TokenSupplyType;
use crate::token::token_type::TokenType;
use crate::transaction::{
AnyTransactionData,
ToTransactionDataProtobuf,
TransactionExecute,
};
use crate::{
AccountId,
Error,
Key,
LedgerId,
Transaction,
TransactionId,
};
pub type TokenCreateTransaction = Transaction<TokenCreateTransactionData>;
#[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 TokenCreateTransactionData {
name: String,
symbol: String,
decimals: u32,
initial_supply: u64,
treasury_account_id: Option<AccountId>,
admin_key: Option<Key>,
kyc_key: Option<Key>,
freeze_key: Option<Key>,
wipe_key: Option<Key>,
supply_key: Option<Key>,
freeze_default: bool,
#[cfg_attr(
feature = "ffi",
serde(with = "serde_with::As::<Option<serde_with::TimestampNanoSeconds>>")
)]
expiration_time: Option<OffsetDateTime>,
auto_renew_account_id: Option<AccountId>,
#[cfg_attr(
feature = "ffi",
serde(with = "serde_with::As::<Option<serde_with::DurationSeconds<i64>>>")
)]
auto_renew_period: Option<Duration>,
token_memo: String,
token_type: TokenType,
token_supply_type: TokenSupplyType,
max_supply: u64,
fee_schedule_key: Option<Key>,
custom_fees: Vec<AnyCustomFee>,
pause_key: Option<Key>,
}
impl Default for TokenCreateTransactionData {
fn default() -> Self {
Self {
name: String::new(),
symbol: String::new(),
decimals: 0,
initial_supply: 0,
treasury_account_id: None,
admin_key: None,
kyc_key: None,
freeze_key: None,
wipe_key: None,
supply_key: None,
freeze_default: false,
expiration_time: None,
auto_renew_account_id: None,
auto_renew_period: Some(Duration::days(90)),
token_memo: String::new(),
token_type: TokenType::FungibleCommon,
token_supply_type: TokenSupplyType::Infinite,
max_supply: 0,
fee_schedule_key: None,
custom_fees: vec![],
pause_key: None,
}
}
}
impl TokenCreateTransaction {
pub fn name(&mut self, name: impl Into<String>) -> &mut Self {
self.body.data.name = name.into();
self
}
pub fn symbol(&mut self, symbol: impl Into<String>) -> &mut Self {
self.body.data.symbol = symbol.into();
self
}
pub fn decimals(&mut self, decimals: u32) -> &mut Self {
self.body.data.decimals = decimals;
self
}
pub fn initial_supply(&mut self, initial_supply: u64) -> &mut Self {
self.body.data.initial_supply = initial_supply;
self
}
pub fn treasury_account_id(&mut self, treasury_account_id: AccountId) -> &mut Self {
self.body.data.treasury_account_id = Some(treasury_account_id);
self
}
pub fn admin_key(&mut self, admin_key: impl Into<Key>) -> &mut Self {
self.body.data.admin_key = Some(admin_key.into());
self
}
pub fn kyc_key(&mut self, kyc_key: impl Into<Key>) -> &mut Self {
self.body.data.kyc_key = Some(kyc_key.into());
self
}
pub fn freeze_key(&mut self, freeze_key: impl Into<Key>) -> &mut Self {
self.body.data.freeze_key = Some(freeze_key.into());
self
}
pub fn wipe_key(&mut self, wipe_key: impl Into<Key>) -> &mut Self {
self.body.data.wipe_key = Some(wipe_key.into());
self
}
pub fn supply_key(&mut self, supply_key: impl Into<Key>) -> &mut Self {
self.body.data.supply_key = Some(supply_key.into());
self
}
pub fn freeze_default(&mut self, freeze_default: bool) -> &mut Self {
self.body.data.freeze_default = freeze_default;
self
}
pub fn expiration_time(&mut self, expiration_time: OffsetDateTime) -> &mut Self {
self.body.data.expiration_time = Some(expiration_time);
self.body.data.auto_renew_period = None;
self
}
pub fn auto_renew_account_id(&mut self, auto_renew_account_id: AccountId) -> &mut Self {
self.body.data.auto_renew_account_id = Some(auto_renew_account_id);
self
}
pub fn auto_renew_period(&mut self, auto_renew_period: Duration) -> &mut Self {
self.body.data.auto_renew_period = Some(auto_renew_period);
self
}
pub fn token_memo(&mut self, memo: impl Into<String>) -> &mut Self {
self.body.data.token_memo = memo.into();
self
}
pub fn token_type(&mut self, token_type: TokenType) -> &mut Self {
self.body.data.token_type = token_type;
self
}
pub fn token_supply_type(&mut self, token_supply_type: TokenSupplyType) -> &mut Self {
self.body.data.token_supply_type = token_supply_type;
self
}
pub fn max_supply(&mut self, max_supply: u64) -> &mut Self {
self.body.data.max_supply = max_supply;
self
}
pub fn fee_schedule_key(&mut self, fee_schedule_key: impl Into<Key>) -> &mut Self {
self.body.data.fee_schedule_key = Some(fee_schedule_key.into());
self
}
pub fn custom_fees(
&mut self,
custom_fees: impl IntoIterator<Item = AnyCustomFee>,
) -> &mut Self {
self.body.data.custom_fees = custom_fees.into_iter().collect();
self
}
pub fn pause_key(&mut self, pause_key: impl Into<Key>) -> &mut Self {
self.body.data.pause_key = Some(pause_key.into());
self
}
}
#[async_trait]
impl TransactionExecute for TokenCreateTransactionData {
fn validate_checksums_for_ledger_id(&self, ledger_id: &LedgerId) -> Result<(), Error> {
self.treasury_account_id.validate_checksum_for_ledger_id(ledger_id)?;
self.auto_renew_account_id.validate_checksum_for_ledger_id(ledger_id)
}
async fn execute(
&self,
channel: Channel,
request: services::Transaction,
) -> Result<tonic::Response<services::TransactionResponse>, tonic::Status> {
TokenServiceClient::new(channel).create_token(request).await
}
}
impl ToTransactionDataProtobuf for TokenCreateTransactionData {
fn to_transaction_data_protobuf(
&self,
_node_account_id: AccountId,
_transaction_id: &TransactionId,
) -> services::transaction_body::Data {
services::transaction_body::Data::TokenCreation(services::TokenCreateTransactionBody {
name: self.name.clone(),
symbol: self.symbol.clone(),
decimals: self.decimals,
initial_supply: self.initial_supply,
treasury: self.treasury_account_id.to_protobuf(),
admin_key: self.admin_key.to_protobuf(),
kyc_key: self.kyc_key.to_protobuf(),
freeze_key: self.freeze_key.to_protobuf(),
wipe_key: self.wipe_key.to_protobuf(),
supply_key: self.supply_key.to_protobuf(),
freeze_default: self.freeze_default,
expiry: self.expiration_time.map(Into::into),
auto_renew_account: self.auto_renew_account_id.to_protobuf(),
auto_renew_period: self.auto_renew_period.map(Into::into),
memo: self.token_memo.clone(),
token_type: self.token_type.to_protobuf().into(),
supply_type: self.token_supply_type.to_protobuf().into(),
max_supply: self.max_supply as i64,
fee_schedule_key: self.fee_schedule_key.to_protobuf(),
custom_fees: self.custom_fees.to_protobuf(),
pause_key: self.pause_key.to_protobuf(),
})
}
}
impl From<TokenCreateTransactionData> for AnyTransactionData {
fn from(transaction: TokenCreateTransactionData) -> Self {
Self::TokenCreate(transaction)
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "ffi")]
mod ffi {
use std::str::FromStr;
use assert_matches::assert_matches;
use time::{
Duration,
OffsetDateTime,
};
use crate::token::custom_fees::{
CustomFee,
FixedFeeData,
};
use crate::token::token_supply_type::TokenSupplyType;
use crate::token::token_type::TokenType;
use crate::transaction::{
AnyTransaction,
AnyTransactionData,
};
use crate::{
AccountId,
Key,
PublicKey,
TokenCreateTransaction,
TokenId,
};
const TOKEN_CREATE_EMPTY: &str = r#"{
"$type": "tokenCreate"
}"#;
const TOKEN_CREATE_TRANSACTION_JSON: &str = r#"{
"$type": "tokenCreate",
"name": "Pound",
"symbol": "LB",
"decimals": 9,
"initialSupply": 1000000000,
"treasuryAccountId": "0.0.1001",
"adminKey": {
"single": "302a300506032b6570032100d1ad76ed9b057a3d3f2ea2d03b41bcd79aeafd611f941924f0f6da528ab066fd"
},
"kycKey": {
"single": "302a300506032b6570032100b5b4d9351ebdf266ef3989aed4fd8f0cfcf24b75ba3d0df19cd3946771b40500"
},
"freezeKey": {
"single": "302a300506032b657003210004e540b5fba8fc1ee1cc5cc450019c578b36311733507fabf4f85bf2744583e7"
},
"wipeKey": {
"single": "302a300506032b657003210099f8981cad75fc7322bf5c89d5f4ce4f2af76b2a63780b22cbce1bfdfa237f4e"
},
"supplyKey": {
"single": "302a300506032b6570032100c80c04aaca1783aafbaf6eba462bac89236ec82ac4db31953329ffbfeacdb88b"
},
"freezeDefault": false,
"expirationTime": 1656352251277559886,
"autoRenewAccountId": "0.0.1002",
"autoRenewPeriod": 7776000,
"tokenMemo": "A memo",
"tokenType": "fungibleCommon",
"tokenSupplyType": "finite",
"maxSupply": 1000000000,
"feeScheduleKey": {
"single": "302a300506032b65700321000cd029bfd4a818de944c21799f4b5f6b5616702d0495520c818d92488e5395fc"
},
"customFees": [
{
"$type": "fixed",
"amount": 1,
"denominatingTokenId": "0.0.7",
"feeCollectorAccountId": "0.0.8",
"allCollectorsAreExempt": false
}
],
"pauseKey": {
"single": "302a300506032b65700321008b020177031eae1e4a721c814b08a3ef2c3f473781a570e9daaf9f7ad27f8967"
}
}"#;
const ADMIN_KEY: &str =
"302a300506032b6570032100d1ad76ed9b057a3d3f2ea2d03b41bcd79aeafd611f941924f0f6da528ab066fd";
const KYC_KEY: &str =
"302a300506032b6570032100b5b4d9351ebdf266ef3989aed4fd8f0cfcf24b75ba3d0df19cd3946771b40500";
const FREEZE_KEY: &str =
"302a300506032b657003210004e540b5fba8fc1ee1cc5cc450019c578b36311733507fabf4f85bf2744583e7";
const WIPE_KEY: &str =
"302a300506032b657003210099f8981cad75fc7322bf5c89d5f4ce4f2af76b2a63780b22cbce1bfdfa237f4e";
const SUPPLY_KEY: &str =
"302a300506032b6570032100c80c04aaca1783aafbaf6eba462bac89236ec82ac4db31953329ffbfeacdb88b";
const FEE_SCHEDULE_KEY: &str =
"302a300506032b65700321000cd029bfd4a818de944c21799f4b5f6b5616702d0495520c818d92488e5395fc";
const PAUSE_KEY: &str =
"302a300506032b65700321008b020177031eae1e4a721c814b08a3ef2c3f473781a570e9daaf9f7ad27f8967";
#[test]
fn it_should_serialize() -> anyhow::Result<()> {
let mut transaction = TokenCreateTransaction::new();
transaction
.name("Pound")
.symbol("LB")
.decimals(9)
.initial_supply(1_000_000_000)
.treasury_account_id(AccountId::from_str("0.0.1001")?)
.admin_key(PublicKey::from_str(ADMIN_KEY)?)
.kyc_key(PublicKey::from_str(KYC_KEY)?)
.freeze_key(PublicKey::from_str(FREEZE_KEY)?)
.wipe_key(PublicKey::from_str(WIPE_KEY)?)
.supply_key(PublicKey::from_str(SUPPLY_KEY)?)
.freeze_default(false)
.expiration_time(OffsetDateTime::from_unix_timestamp_nanos(1656352251277559886)?)
.auto_renew_account_id(AccountId::from_str("0.0.1002")?)
.auto_renew_period(Duration::days(90))
.token_memo("A memo")
.token_type(TokenType::FungibleCommon)
.token_supply_type(TokenSupplyType::Finite)
.max_supply(1_000_000_000)
.fee_schedule_key(PublicKey::from_str(FEE_SCHEDULE_KEY)?)
.custom_fees([CustomFee {
fee: FixedFeeData { amount: 1, denominating_token_id: TokenId::from(7) }.into(),
fee_collector_account_id: Some(AccountId::from(8)),
all_collectors_are_exempt: false,
}])
.pause_key(PublicKey::from_str(PAUSE_KEY)?);
let transaction_json = serde_json::to_string_pretty(&transaction)?;
assert_eq!(transaction_json, TOKEN_CREATE_TRANSACTION_JSON);
Ok(())
}
#[test]
fn it_should_deserialize() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(TOKEN_CREATE_TRANSACTION_JSON)?;
let data = assert_matches!(transaction.body.data, AnyTransactionData::TokenCreate(transaction) => transaction);
assert_eq!(data.name, "Pound");
assert_eq!(data.symbol, "LB");
assert_eq!(data.decimals, 9);
assert_eq!(data.initial_supply, 1_000_000_000);
assert_eq!(data.freeze_default, false);
assert_eq!(
data.expiration_time.unwrap(),
OffsetDateTime::from_unix_timestamp_nanos(1656352251277559886)?
);
assert_eq!(data.auto_renew_period.unwrap(), Duration::days(90));
assert_eq!(data.token_memo, "A memo");
assert_eq!(data.token_type, TokenType::FungibleCommon);
assert_eq!(data.token_supply_type, TokenSupplyType::Finite);
assert_eq!(data.max_supply, 1_000_000_000);
assert_eq!(data.treasury_account_id, Some(AccountId::from(1001)));
assert_eq!(data.auto_renew_account_id, Some(AccountId::from(1002)));
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 kyc_key =
assert_matches!(data.kyc_key.unwrap(), Key::Single(public_key) => public_key);
assert_eq!(kyc_key, PublicKey::from_str(KYC_KEY)?);
let freeze_key =
assert_matches!(data.freeze_key.unwrap(), Key::Single(public_key) => public_key);
assert_eq!(freeze_key, PublicKey::from_str(FREEZE_KEY)?);
let wipe_key =
assert_matches!(data.wipe_key.unwrap(), Key::Single(public_key) => public_key);
assert_eq!(wipe_key, PublicKey::from_str(WIPE_KEY)?);
let supply_key =
assert_matches!(data.supply_key.unwrap(), Key::Single(public_key) => public_key);
assert_eq!(supply_key, PublicKey::from_str(SUPPLY_KEY)?);
let fee_schedule_key = assert_matches!(data.fee_schedule_key.unwrap(), Key::Single(public_key) => public_key);
assert_eq!(fee_schedule_key, PublicKey::from_str(FEE_SCHEDULE_KEY)?);
let pause_key =
assert_matches!(data.pause_key.unwrap(), Key::Single(public_key) => public_key);
assert_eq!(pause_key, PublicKey::from_str(PAUSE_KEY)?);
assert_eq!(
data.custom_fees,
[CustomFee {
fee: FixedFeeData { amount: 1, denominating_token_id: TokenId::from(7) }.into(),
fee_collector_account_id: Some(AccountId::from(8)),
all_collectors_are_exempt: false,
}]
);
Ok(())
}
#[test]
#[ignore = "auto renew period is `None`"]
fn it_should_deserialize_empty() -> anyhow::Result<()> {
let transaction: AnyTransaction = serde_json::from_str(TOKEN_CREATE_EMPTY)?;
let data = assert_matches!(transaction.body.data, AnyTransactionData::TokenCreate(transaction) => transaction);
assert_eq!(data.auto_renew_period.unwrap(), Duration::days(90));
assert_eq!(data.token_type, TokenType::FungibleCommon);
assert_eq!(data.token_supply_type, TokenSupplyType::Infinite);
Ok(())
}
}
}