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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use crate::*;

use solana_client::rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig};
use solana_sdk::commitment_config::{CommitmentConfig, CommitmentLevel};
use solana_sdk::signer::Signer;

use std::sync::Arc;

#[derive(Default, Debug, Clone)]
pub struct FunctionRoutineFilters {
    pub attestation_queue: Option<Pubkey>,
    pub authority: Option<Pubkey>,
    pub metadata: Option<Vec<u8>>,
    pub is_enabled: Option<bool>,
    // Note: This will not catch functions for which the verifier fetching
    // is the secondary oracle. This is because the verifier is not stored
    // on the function account but on the queue account.
    pub queue_idx: Option<u32>,
}

impl FunctionRoutineFilters {
    pub fn to_vec(&self) -> Vec<solana_client::rpc_filter::RpcFilterType> {
        let mut filters = vec![FunctionRoutineAccountData::get_discriminator_filter()];

        // AttestationQueue Filter
        if let Some(attestation_queue) = &self.attestation_queue {
            filters.push(FunctionRoutineAccountData::get_queue_filter(
                attestation_queue,
            ));
        }

        // Authority Filter
        if let Some(authority) = &self.authority {
            filters.push(FunctionRoutineAccountData::get_authority_filter(authority));
        }

        // Metadata Filter
        if let Some(metadata) = &self.metadata {
            filters.push(FunctionRoutineAccountData::get_metadata_filter(
                metadata.clone(),
            ));
        }

        // Is Enabled Filter
        if let Some(is_enabled) = &self.is_enabled {
            if *is_enabled {
                filters.push(FunctionRoutineAccountData::get_is_enabled_filter());
            }
        }

        // Queue Idx Filter
        if let Some(queue_idx) = &self.queue_idx {
            filters.push(FunctionRoutineAccountData::get_queue_idx_filter(queue_idx));
        }

        filters
    }
}

impl FunctionRoutineAccountData {
    /////////////////////////////////////////////////////////////
    /// Client Methods
    /////////////////////////////////////////////////////////////

    pub async fn get_program_accounts(
        rpc: &solana_client::nonblocking::rpc_client::RpcClient,
        filters: FunctionRoutineFilters,
        commitment: Option<CommitmentLevel>,
    ) -> Result<Vec<(Pubkey, FunctionRoutineAccountData)>, SbError> {
        let mut routines = vec![];

        let accounts = rpc
            .get_program_accounts_with_config(
                &SWITCHBOARD_ATTESTATION_PROGRAM_ID,
                RpcProgramAccountsConfig {
                    filters: Some(filters.to_vec()),
                    account_config: RpcAccountInfoConfig {
                        encoding: Some(solana_account_decoder::UiAccountEncoding::Base64Zstd),
                        commitment: Some(CommitmentConfig {
                            commitment: commitment.unwrap_or(CommitmentLevel::Processed),
                        }),
                        ..Default::default()
                    },

                    ..Default::default()
                },
            )
            .await
            .map_err(|e| SbError::CustomError {
                message: "Failed to get program accounts".to_string(),
                source: Arc::new(e),
            })?;

        for (pubkey, account) in accounts {
            if let Ok(routine_data) =
                FunctionRoutineAccountData::try_deserialize(&mut &account.data[..])
            {
                routines.push((pubkey, routine_data));
            }
        }

        Ok(routines)
    }

    /////////////////////////////////////////////////////////////
    /// Fetch Methods
    /////////////////////////////////////////////////////////////

    pub fn fetch(
        client: &solana_client::rpc_client::RpcClient,
        pubkey: Pubkey,
    ) -> std::result::Result<Self, switchboard_common::SbError> {
        crate::client::fetch_borsh_account(client, pubkey)
    }

    pub async fn fetch_async(
        client: &solana_client::nonblocking::rpc_client::RpcClient,
        pubkey: Pubkey,
    ) -> std::result::Result<Self, switchboard_common::SbError> {
        crate::client::fetch_borsh_account_async(client, pubkey).await
    }

    pub fn fetch_sync<T: solana_sdk::client::SyncClient>(
        client: &T,
        pubkey: Pubkey,
    ) -> std::result::Result<Self, switchboard_common::SbError> {
        crate::client::fetch_borsh_account_sync(client, pubkey)
    }

    //

    pub fn get_discriminator_filter() -> solana_client::rpc_filter::RpcFilterType {
        solana_client::rpc_filter::RpcFilterType::Memcmp(
            solana_client::rpc_filter::Memcmp::new_raw_bytes(
                0,
                FunctionRoutineAccountData::discriminator().to_vec(),
            ),
        )
    }

    pub fn get_authority_filter(
        authority_pubkey: &Pubkey,
    ) -> solana_client::rpc_filter::RpcFilterType {
        solana_client::rpc_filter::RpcFilterType::Memcmp(
            solana_client::rpc_filter::Memcmp::new_raw_bytes(
                419,
                authority_pubkey.to_bytes().into(),
            ),
        )
    }

    pub fn get_queue_filter(queue_pubkey: &Pubkey) -> solana_client::rpc_filter::RpcFilterType {
        solana_client::rpc_filter::RpcFilterType::Memcmp(
            solana_client::rpc_filter::Memcmp::new_raw_bytes(515, queue_pubkey.to_bytes().into()),
        )
    }

    pub fn get_queue_idx_filter(queue_idx: &u32) -> solana_client::rpc_filter::RpcFilterType {
        solana_client::rpc_filter::RpcFilterType::Memcmp(
            solana_client::rpc_filter::Memcmp::new_raw_bytes(611, queue_idx.to_le_bytes().to_vec()),
        )
    }

    pub fn get_is_enabled_filter() -> solana_client::rpc_filter::RpcFilterType {
        solana_client::rpc_filter::RpcFilterType::Memcmp(
            solana_client::rpc_filter::Memcmp::new_raw_bytes(344, 0u8.to_le_bytes().to_vec()),
        )
    }

    pub fn get_metadata_filter(metadata: Vec<u8>) -> solana_client::rpc_filter::RpcFilterType {
        solana_client::rpc_filter::RpcFilterType::Memcmp(
            solana_client::rpc_filter::Memcmp::new_raw_bytes(72, metadata),
        )
    }

    pub fn get_schedule(&self) -> Option<cron::Schedule> {
        if self.schedule[0] == 0 {
            return None;
        }
        let every_second = cron::Schedule::try_from("* * * * * *").unwrap();
        let schedule = std::str::from_utf8(&self.schedule)
            .unwrap_or("* * * * * *")
            .trim_end_matches('\0');
        let schedule = cron::Schedule::try_from(schedule);
        Some(schedule.unwrap_or(every_second))
    }

    pub fn get_last_execution_datetime(&self) -> chrono::DateTime<chrono::Utc> {
        chrono::NaiveDateTime::from_timestamp_opt(self.last_execution_timestamp, 0)
            .unwrap()
            .and_utc()
    }

    pub fn get_next_execution_datetime(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        let schedule = self.get_schedule()?;

        // If we havent ever executed, use the current timestamp
        let last_execution_timestamp = if self.last_execution_timestamp > 0 {
            self.last_execution_timestamp
        } else {
            unix_timestamp()
        };
        let last_execution_datetime =
            chrono::NaiveDateTime::from_timestamp_opt(last_execution_timestamp, 0)
                .unwrap()
                .and_utc();

        schedule.after(&last_execution_datetime).next()
    }

    pub fn should_execute(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
        let schedule = self.get_schedule();
        if schedule.is_none() {
            return false;
        }
        if self.last_execution_timestamp == 0 {
            return true;
        }
        let dt = self.get_last_execution_datetime();
        let next_trigger_time = schedule.unwrap().after(&dt).next();
        if next_trigger_time.is_none() {
            return false;
        }
        let next_trigger_time = next_trigger_time.unwrap();
        if next_trigger_time > now {
            return false;
        }
        true
    }

    pub fn calc_container_params_hash(container_params: &Vec<u8>) -> [u8; 32] {
        solana_program::hash::hash(container_params).to_bytes()
    }

    pub fn get_container_params_hash(&self) -> [u8; 32] {
        solana_program::hash::hash(&self.container_params).to_bytes()
    }
}