1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use crate::{protocol::ProtocolParameters, Error};
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, packable::Packable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[packable(unpack_error = Error)]
#[packable(unpack_visitor = ProtocolParameters)]
pub struct TreasuryOutput {
#[packable(verify_with = verify_amount_packable)]
amount: u64,
}
impl TreasuryOutput {
pub const KIND: u8 = 2;
pub fn new(amount: u64, token_supply: u64) -> Result<Self, Error> {
verify_amount::<true>(&amount, &token_supply)?;
Ok(Self { amount })
}
#[inline(always)]
pub fn amount(&self) -> u64 {
self.amount
}
}
fn verify_amount<const VERIFY: bool>(amount: &u64, token_supply: &u64) -> Result<(), Error> {
if VERIFY && amount > token_supply {
Err(Error::InvalidTreasuryOutputAmount(*amount))
} else {
Ok(())
}
}
fn verify_amount_packable<const VERIFY: bool>(
amount: &u64,
protocol_parameters: &ProtocolParameters,
) -> Result<(), Error> {
verify_amount::<VERIFY>(amount, &protocol_parameters.token_supply())
}
#[cfg(feature = "dto")]
#[allow(missing_docs)]
pub mod dto {
use serde::{Deserialize, Serialize};
use super::*;
use crate::error::dto::DtoError;
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct TreasuryOutputDto {
#[serde(rename = "type")]
pub kind: u8,
pub amount: String,
}
impl From<&TreasuryOutput> for TreasuryOutputDto {
fn from(value: &TreasuryOutput) -> Self {
Self {
kind: TreasuryOutput::KIND,
amount: value.amount().to_string(),
}
}
}
impl TreasuryOutput {
pub fn try_from_dto(value: &TreasuryOutputDto, token_supply: u64) -> Result<TreasuryOutput, DtoError> {
Ok(TreasuryOutput::new(
value
.amount
.parse::<u64>()
.map_err(|_| DtoError::InvalidField("amount"))?,
token_supply,
)?)
}
}
}