cronos_network/state/
snapshot.rs

1use {
2    super::{Node, SnapshotEntry},
3    crate::{pda::PDA, state::SnapshotEntryAccount},
4    anchor_lang::{prelude::*, AnchorDeserialize},
5    anchor_spl::token::TokenAccount,
6    std::convert::TryFrom,
7};
8
9pub const SEED_SNAPSHOT: &[u8] = b"snapshot";
10
11/**
12 * Snapshot
13 */
14
15#[account]
16#[derive(Debug)]
17pub struct Snapshot {
18    pub id: u64,
19    pub node_count: u64,
20    pub stake_total: u64,
21    pub status: SnapshotStatus,
22}
23
24impl Snapshot {
25    pub fn pda(id: u64) -> PDA {
26        Pubkey::find_program_address(&[SEED_SNAPSHOT, id.to_be_bytes().as_ref()], &crate::ID)
27    }
28}
29
30impl TryFrom<Vec<u8>> for Snapshot {
31    type Error = Error;
32    fn try_from(data: Vec<u8>) -> std::result::Result<Self, Self::Error> {
33        Snapshot::try_deserialize(&mut data.as_slice())
34    }
35}
36
37/**
38 * SnapshotAccount
39 */
40
41pub trait SnapshotAccount {
42    fn new(&mut self, id: u64) -> Result<()>;
43
44    fn capture(
45        &mut self,
46        entry: &mut Account<SnapshotEntry>,
47        node: &Account<Node>,
48        stake: &Account<TokenAccount>,
49    ) -> Result<()>;
50}
51
52impl SnapshotAccount for Account<'_, Snapshot> {
53    fn new(&mut self, id: u64) -> Result<()> {
54        self.id = id;
55        self.node_count = 0;
56        self.status = SnapshotStatus::InProgress;
57        Ok(())
58    }
59
60    fn capture(
61        &mut self,
62        entry: &mut Account<SnapshotEntry>,
63        node: &Account<Node>,
64        stake: &Account<TokenAccount>,
65    ) -> Result<()> {
66        // Record the new snapshot entry
67        entry.new(
68            self.node_count,
69            node.delegate,
70            self.key(),
71            self.stake_total,
72            stake.amount,
73        )?;
74
75        // Update the snapshot's entry count
76        self.node_count = self.node_count.checked_add(1).unwrap();
77
78        // Update the sum stake amount
79        self.stake_total = self.stake_total.checked_add(stake.amount).unwrap();
80
81        Ok(())
82    }
83}
84
85/**
86 * SnapshotStatus
87 */
88#[derive(AnchorDeserialize, AnchorSerialize, Clone, Debug, PartialEq)]
89pub enum SnapshotStatus {
90    Archived { ts: i64 },
91    Current,
92    InProgress,
93}