penumbra_governance/
proposal_nft.rs

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use std::str::FromStr;

use regex::Regex;

use penumbra_asset::asset;

/// Unbonding tokens represent staking tokens that are currently unbonding and
/// subject to slashing.
///
/// Unbonding tokens are parameterized by the validator identity, the epoch at
/// which unbonding began, and the epoch at which unbonding ends.
pub struct ProposalNft {
    proposal_id: u64,
    proposal_state: Kind,
    base_denom: asset::Metadata,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    Deposit,
    UnbondingDeposit,
    Slashed,
    Failed,
    Passed,
}

impl Kind {
    pub const fn display_static(&self) -> &'static str {
        match self {
            Kind::Deposit => "deposit",
            Kind::UnbondingDeposit => "unbonding_deposit",
            Kind::Slashed => "slashed",
            Kind::Failed => "failed",
            Kind::Passed => "passed",
        }
    }
}

impl FromStr for Kind {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "deposit" => Ok(Kind::Deposit),
            "unbonding_deposit" => Ok(Kind::UnbondingDeposit),
            "slashed" => Ok(Kind::Slashed),
            "failed" => Ok(Kind::Failed),
            "passed" => Ok(Kind::Passed),
            _ => Err(anyhow::anyhow!("invalid proposal token state")),
        }
    }
}

impl ProposalNft {
    fn new(proposal_id: u64, proposal_state: Kind) -> Self {
        // This format string needs to be in sync with the asset registry
        let base_denom = asset::REGISTRY
            .parse_denom(&format!(
                "proposal_{}_{}",
                proposal_id,
                proposal_state.display_static()
            ))
            .expect("base denom format is valid");
        ProposalNft {
            proposal_id,
            proposal_state,
            base_denom,
        }
    }

    /// Make a new proposal NFT in the deposit state.
    pub fn deposit(proposal_id: u64) -> Self {
        Self::new(proposal_id, Kind::Deposit)
    }

    /// Make a new proposal NFT in the unbonding deposit state.
    pub fn unbonding_deposit(proposal_id: u64) -> Self {
        Self::new(proposal_id, Kind::UnbondingDeposit)
    }

    /// Make a new proposal NFT in the slashed state.
    pub fn slashed(proposal_id: u64) -> Self {
        Self::new(proposal_id, Kind::Slashed)
    }

    /// Make a new proposal NFT in the failed state.
    pub fn failed(proposal_id: u64) -> Self {
        Self::new(proposal_id, Kind::Failed)
    }

    /// Make a new proposal NFT in the passed state.
    pub fn passed(proposal_id: u64) -> Self {
        Self::new(proposal_id, Kind::Passed)
    }

    /// Get the base denomination for this delegation token.
    pub fn denom(&self) -> asset::Metadata {
        self.base_denom.clone()
    }

    /// Get the default display denomination for this delegation token.
    pub fn default_unit(&self) -> asset::Unit {
        self.base_denom.default_unit()
    }

    /// Get the asset ID for this delegation token.
    pub fn id(&self) -> asset::Id {
        self.base_denom.id()
    }

    /// Get the proposal ID for this proposal token.
    pub fn proposal_id(&self) -> u64 {
        self.proposal_id
    }

    /// Get the proposal state for this proposal token.
    pub fn proposal_state(&self) -> Kind {
        self.proposal_state
    }
}

impl TryFrom<asset::Metadata> for ProposalNft {
    type Error = anyhow::Error;

    fn try_from(base_denom: asset::Metadata) -> Result<Self, Self::Error> {
        let base_string = base_denom.to_string();

        // Note: this regex must be in sync with asset::REGISTRY
        // The data capture group is used by asset::REGISTRY
        let captures = Regex::new("^proposal_(?P<data>(?P<proposal_id>[0-9]+)_(?P<proposal_state>deposit|unbonding_deposit|passed|failed|slashed))$")
            .expect("regex is valid")
            .captures(base_string.as_ref())
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "base denom {} is not a proposal token",
                    base_denom.to_string()
                )
            })?;

        let proposal_id = captures
            .name("proposal_id")
            .expect("proposal_id is a named capture")
            .as_str()
            .parse()?;

        let proposal_state = captures
            .name("proposal_state")
            .expect("proposal_state is a named capture")
            .as_str()
            .parse()?;

        Ok(Self {
            base_denom,
            proposal_state,
            proposal_id,
        })
    }
}

impl FromStr for ProposalNft {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        asset::REGISTRY
            .parse_denom(s)
            .ok_or_else(|| anyhow::anyhow!("could not parse {} as base denomination", s))?
            .try_into()
    }
}

impl std::fmt::Display for ProposalNft {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.base_denom.fmt(f)
    }
}

impl std::fmt::Debug for ProposalNft {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.base_denom.fmt(f)
    }
}

impl PartialEq for ProposalNft {
    fn eq(&self, other: &Self) -> bool {
        self.base_denom.eq(&other.base_denom)
    }
}

impl Eq for ProposalNft {}

impl std::hash::Hash for ProposalNft {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.base_denom.hash(state)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn proposal_token_denomination_round_trip() {
        let tokens = [
            ProposalNft::deposit(1),
            ProposalNft::unbonding_deposit(1),
            ProposalNft::passed(1),
            ProposalNft::failed(1),
            ProposalNft::slashed(1),
        ];

        for token in tokens {
            let denom = token.to_string();
            println!("denom: {denom}");
            let token2 = ProposalNft::from_str(&denom).unwrap();
            let denom2 = token2.to_string();

            assert_eq!(denom, denom2);
            assert_eq!(token, token2);
        }
    }
}