pcli/command/view/
staked.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
use std::collections::BTreeMap;

use anyhow::Result;
use comfy_table::{presets, Table};
use futures::TryStreamExt;
use tonic::transport::Channel;

use penumbra_asset::{Value, STAKING_TOKEN_ASSET_ID};
use penumbra_keys::FullViewingKey;
use penumbra_proto::core::component::stake::v1::{
    query_service_client::QueryServiceClient as StakeQueryServiceClient, ValidatorInfoRequest,
};
use penumbra_stake::{validator, DelegationToken};
use penumbra_view::ViewClient;

#[derive(Debug, clap::Parser)]
pub struct StakedCmd {}

impl StakedCmd {
    pub fn offline(&self) -> bool {
        false
    }

    pub async fn exec(
        &self,
        _fvk: &FullViewingKey,
        view_client: &mut impl ViewClient,
        pd_channel: Channel,
    ) -> Result<()> {
        let asset_cache = view_client.assets().await?;

        let mut client = StakeQueryServiceClient::new(pd_channel);

        let validators = client
            .validator_info(ValidatorInfoRequest {
                show_inactive: true,
                ..Default::default()
            })
            .await?
            .into_inner()
            .try_collect::<Vec<_>>()
            .await?
            .into_iter()
            .map(TryInto::try_into)
            .collect::<Result<Vec<validator::Info>, _>>()?;

        let notes = view_client.unspent_notes_by_asset_and_address().await?;
        let mut total = 0u128;

        let mut table = Table::new();
        table.load_preset(presets::NOTHING);
        table.set_header(vec!["Name", "Value", "Exch. Rate", "Tokens"]);
        table
            .get_column_mut(1)
            .expect("column 1 exists")
            .set_cell_alignment(comfy_table::CellAlignment::Right);

        for (asset_id, notes_by_address) in notes.iter() {
            let dt = if let Some(Ok(dt)) = asset_cache
                .get(asset_id)
                .map(|denom| DelegationToken::try_from(denom.clone()))
            {
                dt
            } else {
                continue;
            };

            let delegation = Value {
                amount: notes_by_address
                    .values()
                    .flat_map(|notes| notes.iter().map(|n| n.note.amount()))
                    .sum(),
                asset_id: dt.id(),
            };

            let info = match validators
                .iter()
                .find(|v| v.validator.identity_key == dt.validator())
            {
                Some(info) => info,
                None => {
                    table.add_row(vec![
                        "missing data".to_string(),
                        "missing data".to_string(),
                        "missing data".to_string(),
                        delegation.format(&asset_cache),
                    ]);
                    continue;
                }
            };

            let unbonded = Value {
                amount: info
                    .rate_data
                    // TODO fix with new rate calcs
                    .unbonded_amount(delegation.amount)
                    .into(),
                asset_id: *STAKING_TOKEN_ASSET_ID,
            };

            let rate = {
                let validator_exchange_rate = info.rate_data.validator_exchange_rate.value() as f64;
                validator_exchange_rate / 1_0000_0000.0
            };

            table.add_row(vec![
                info.validator.name.clone(),
                unbonded.format(&asset_cache),
                format!("{rate:.4}"),
                delegation.format(&asset_cache),
            ]);

            total += u128::from(unbonded.amount);
        }

        let unbonded = Value {
            amount: notes
                .get(&*STAKING_TOKEN_ASSET_ID)
                .unwrap_or(&BTreeMap::default())
                .values()
                .flat_map(|notes| notes.iter().map(|n| u128::from(n.note.amount())))
                .sum::<u128>()
                .into(),
            asset_id: *STAKING_TOKEN_ASSET_ID,
        };

        total += u128::from(unbonded.amount);

        table.add_row(vec![
            "Unbonded Stake".to_string(),
            unbonded.format(&asset_cache),
            format!("{:.4}", 1.0),
            unbonded.format(&asset_cache),
        ]);

        let total = Value {
            amount: total.into(),
            asset_id: *STAKING_TOKEN_ASSET_ID,
        };

        table.add_row(vec![
            "Total".to_string(),
            total.format(&asset_cache),
            String::new(),
            String::new(),
        ]);
        println!("{table}");

        Ok(())
    }
}