use hedera_proto::services;
use time::OffsetDateTime;
use crate::protobuf::ToProtobuf;
use crate::{
AccountId,
FromProtobuf,
Hbar,
};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "ffi", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "ffi", serde(rename_all = "camelCase"))]
pub struct StakingInfo {
pub decline_staking_reward: bool,
#[cfg_attr(
feature = "ffi",
serde(with = "serde_with::As::<Option<serde_with::TimestampNanoSeconds>>")
)]
pub stake_period_start: Option<OffsetDateTime>,
pub pending_reward: Hbar,
pub staked_to_me: Hbar,
pub staked_account_id: Option<AccountId>,
pub staked_node_id: Option<u64>,
}
impl StakingInfo {
pub fn from_bytes(bytes: &[u8]) -> crate::Result<Self> {
FromProtobuf::from_bytes(bytes)
}
#[must_use]
pub fn to_bytes(&self) -> Vec<u8> {
ToProtobuf::to_bytes(self)
}
}
impl FromProtobuf<services::StakingInfo> for StakingInfo {
fn from_protobuf(pb: services::StakingInfo) -> crate::Result<Self> {
let (staked_account_id, staked_node_id) = match pb.staked_id {
Some(services::staking_info::StakedId::StakedAccountId(id)) => {
(Some(AccountId::from_protobuf(id)?), None)
}
Some(services::staking_info::StakedId::StakedNodeId(id)) => (None, Some(id as u64)),
None => (None, None),
};
Ok(Self {
decline_staking_reward: pb.decline_reward,
stake_period_start: pb.stake_period_start.map(Into::into),
pending_reward: Hbar::from_tinybars(pb.pending_reward),
staked_to_me: Hbar::from_tinybars(pb.staked_to_me),
staked_account_id,
staked_node_id,
})
}
}
impl ToProtobuf for StakingInfo {
type Protobuf = services::StakingInfo;
fn to_protobuf(&self) -> Self::Protobuf {
services::StakingInfo {
decline_reward: self.decline_staking_reward,
stake_period_start: self.stake_period_start.map(Into::into),
pending_reward: self.pending_reward.to_tinybars(),
staked_to_me: self.staked_to_me.to_tinybars(),
staked_id: self
.staked_node_id
.map(|it| it as i64)
.map(services::staking_info::StakedId::StakedNodeId)
.or_else(|| {
self.staked_account_id
.to_protobuf()
.map(services::staking_info::StakedId::StakedAccountId)
}),
}
}
}