bee_block/input/
treasury.rs

1// Copyright 2020-2021 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use core::str::FromStr;
5
6use derive_more::{Deref, From};
7
8use crate::{payload::milestone::MilestoneId, Error};
9
10/// [`TreasuryInput`] is an input which references a milestone which generated a
11/// [`TreasuryOutput`](crate::output::TreasuryOutput).
12#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, From, Deref, packable::Packable)]
13pub struct TreasuryInput(MilestoneId);
14
15impl TreasuryInput {
16    /// The input kind of a [`TreasuryInput`].
17    pub const KIND: u8 = 1;
18
19    /// Creates a new [`TreasuryInput`].
20    pub fn new(id: MilestoneId) -> Self {
21        Self(id)
22    }
23
24    /// Returns the milestones id of a [`TreasuryInput`].
25    pub fn milestone_id(&self) -> &MilestoneId {
26        &self.0
27    }
28}
29
30#[cfg(feature = "serde")]
31string_serde_impl!(TreasuryInput);
32
33impl FromStr for TreasuryInput {
34    type Err = Error;
35
36    fn from_str(s: &str) -> Result<Self, Self::Err> {
37        Ok(TreasuryInput(MilestoneId::from_str(s)?))
38    }
39}
40
41impl core::fmt::Display for TreasuryInput {
42    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
43        write!(f, "{}", self.0)
44    }
45}
46
47impl core::fmt::Debug for TreasuryInput {
48    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
49        write!(f, "TreasuryInput({})", self.0)
50    }
51}
52
53#[cfg(feature = "dto")]
54#[allow(missing_docs)]
55pub mod dto {
56    use serde::{Deserialize, Serialize};
57
58    use super::*;
59    use crate::error::dto::DtoError;
60
61    /// Describes an input which references an unspent treasury output to consume.
62    #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
63    pub struct TreasuryInputDto {
64        #[serde(rename = "type")]
65        pub kind: u8,
66        #[serde(rename = "milestoneId")]
67        pub milestone_id: String,
68    }
69
70    impl From<&TreasuryInput> for TreasuryInputDto {
71        fn from(value: &TreasuryInput) -> Self {
72            TreasuryInputDto {
73                kind: TreasuryInput::KIND,
74                milestone_id: value.milestone_id().to_string(),
75            }
76        }
77    }
78
79    impl TryFrom<&TreasuryInputDto> for TreasuryInput {
80        type Error = DtoError;
81
82        fn try_from(value: &TreasuryInputDto) -> Result<Self, Self::Error> {
83            Ok(TreasuryInput::new(
84                value
85                    .milestone_id
86                    .parse::<MilestoneId>()
87                    .map_err(|_| DtoError::InvalidField("milestoneId"))?,
88            ))
89        }
90    }
91}