penumbra_shielded_pool/genesis/
allocation.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
use penumbra_asset::{
    asset::{self, Metadata, Unit},
    Value,
};
use penumbra_keys::Address;
use penumbra_num::Amount;
use penumbra_proto::{penumbra::core::component::shielded_pool::v1 as pb, DomainType};
use serde::{Deserialize, Serialize};

/// A (transparent) genesis allocation.
#[derive(Clone, Serialize, Deserialize)]
#[serde(
    try_from = "pb::genesis_content::Allocation",
    into = "pb::genesis_content::Allocation"
)]
pub struct Allocation {
    pub raw_amount: Amount,
    pub raw_denom: String,
    pub address: Address,
}

impl Allocation {
    pub fn denom(&self) -> Metadata {
        self.unit().base()
    }

    pub fn unit(&self) -> Unit {
        asset::REGISTRY.parse_unit(&self.raw_denom)
    }

    pub fn amount(&self) -> Amount {
        let unit = self.unit();
        self.raw_amount * (10u128.pow(unit.exponent().into()).into())
    }

    pub fn value(&self) -> Value {
        Value {
            amount: self.amount(),
            asset_id: self.unit().id(),
        }
    }
}

impl From<Allocation> for pb::genesis_content::Allocation {
    fn from(a: Allocation) -> Self {
        pb::genesis_content::Allocation {
            amount: Some(a.raw_amount.into()),
            denom: a.raw_denom,
            address: Some(a.address.into()),
        }
    }
}

impl TryFrom<pb::genesis_content::Allocation> for Allocation {
    type Error = anyhow::Error;

    fn try_from(msg: pb::genesis_content::Allocation) -> Result<Self, Self::Error> {
        Ok(Allocation {
            raw_amount: msg
                .amount
                .ok_or_else(|| anyhow::anyhow!("missing amount field in proto"))?
                .try_into()?,
            raw_denom: msg.denom,
            address: msg
                .address
                .ok_or_else(|| anyhow::anyhow!("missing address field in proto"))?
                .try_into()?,
        })
    }
}

// Implement Debug manually so we can use the Display impl for the address,
// rather than dumping all the internal address components.
impl std::fmt::Debug for Allocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Allocation")
            .field("amount", &self.raw_amount)
            .field("denom", &self.raw_denom)
            .field("address", &self.address.to_string())
            .finish()
    }
}

impl DomainType for Allocation {
    type Proto = pb::genesis_content::Allocation;
}