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
use quick_protobuf::message::MessageWrite;
use quick_protobuf::writer::serialize_into_vec;
use solana_program::pubkey::Pubkey;
use solana_program::sysvar::Sysvar;
use solana_program::sysvar::rent;
use solana_program::{account_info::AccountInfo, msg, program_error::ProgramError};
use std::clone::Clone;
use switchboard_protos::protos::aggregator_state::AggregatorState;
use switchboard_protos::protos::aggregator_state::mod_AggregatorState;
use switchboard_protos::protos::fulfillment_manager::FulfillmentManagerState;
use switchboard_protos::protos::fulfillment_manager::mod_FulfillmentManagerState;
use switchboard_protos::protos::switchboard_account_types::SwitchboardAccountType;
use zerocopy::{AsBytes, FromBytes, LayoutVerified};

pub type PubkeyBuffer = [u8; 32];

#[repr(C)]
#[derive(Default,AsBytes,FromBytes,Clone,Debug)]
pub struct FastRoundResult {
    pub num_success: i32,
    pub num_error: i32,
    pub result: f64,
    pub round_open_slot: u64,
    pub round_open_timestamp: i64,
    pub min_response: f64,
    pub max_response: f64,
}

#[repr(C)]
#[derive(Default,AsBytes,FromBytes,Clone,Debug)]
pub struct FastRoundResultAccountData {
    pub parent: PubkeyBuffer,
    pub result: FastRoundResult,
}

pub fn fast_from_bytes<T: Sized + AsBytes + FromBytes + Clone>(bytes: &[u8])
 -> Result<LayoutVerified<&[u8], T>, ProgramError> {
    let (res, _) = LayoutVerified::<&[u8], T>::new_from_prefix(bytes)
        .ok_or(ProgramError::InvalidAccountData)?;
    return Ok(res);
}

// pub fn borsh_safe_serialize<T: BorshSerialize>(state: &T, type_indicator: SwitchboardAccountType) -> Vec<u8> {
    // msg!("borsh serialize");
    // let mut bytes = state.try_to_vec().unwrap();
    // let size: usize = bytes.len();
    // let mut res = vec![type_indicator as u8];
    // res.append(&mut size.to_le_bytes().to_vec());
    // res.append(&mut bytes);
    // return res;
// }
//
// pub fn borsh_safe_deserialize<T: BorshDeserialize>(bytes: &[u8]) -> Result<T, ProgramError> {
    // let size_buf: &[u8] = &bytes[1..9];
    // let size = usize::from_le_bytes(size_buf.try_into().unwrap());
    // let buf = &bytes[9..size + 9];
    // let res = &buf[..size].to_vec();
    // T::try_from_slice(res).map_err(|_| ProgramError::InvalidAccountData)
// }

pub fn save_state<T: MessageWrite>(
    account: &AccountInfo,
    state: &T,
    type_indicator: SwitchboardAccountType,
) -> Result<Vec<u8>, ProgramError> {
    let mut to = account.try_borrow_mut_data()?;
    let mut bytes = serialize_into_vec(state).map_err(|_| ProgramError::InvalidAccountData)?;
    let mut res = vec![type_indicator as u8];
    res.append(&mut bytes);
    to[..res.len()].copy_from_slice(&res);
    Ok([].to_vec())
}

pub fn save_state_to_buffer<T: MessageWrite>(
    state: &T,
    type_indicator: SwitchboardAccountType,
) -> Result<Vec<u8>, ProgramError> {
    let bytes = serialize_into_vec(state).map_err(|_| ProgramError::InvalidAccountData)?;
    Ok(format_buffer(&bytes, type_indicator))
}

pub fn format_buffer(from: &[u8], type_indicator: SwitchboardAccountType) -> Vec<u8> {
    let mut res = vec![type_indicator as u8];
    res.extend(from);
    res
}

pub fn memcpy(to: &mut [u8], from: &[u8]) {
    to[..from.len()].copy_from_slice(&from);
}

pub fn is_account_rent_exempt(
    rent_sysvar_account: &AccountInfo,
    account: &AccountInfo,
) -> Result<bool, ProgramError> {
    let data_len = account.try_data_len()?;
    let lamports = account.try_lamports()?;
    is_rent_exempt(rent_sysvar_account, lamports, data_len)
}

pub fn is_rent_exempt(
    rent_sysvar_account: &AccountInfo,
    lamports: u64,
    data_len: usize,
) -> Result<bool, ProgramError> {
    if *rent_sysvar_account.key != rent::ID {
        msg!("Incorrect rent sysvar account.");
        return Err(ProgramError::IncorrectProgramId);
    }
    let rent = rent::Rent::from_account_info(rent_sysvar_account)?;
    if rent.is_exempt(lamports, data_len as usize) {
        return Ok(true);
    }
    Ok(false)
}

pub trait ProgramAction {
    fn validate(&self) -> Result<(), ProgramError>;
    fn actuate(&mut self) -> Result<Vec<u8>, ProgramError>;
}

pub struct AccountType {}

impl AccountType {
    pub fn check_account(
        account: &AccountInfo,
        type_indicator: SwitchboardAccountType,
    ) -> Result<(), ProgramError> {
        let buffer = account.try_borrow_data()?;
        AccountType::strip_type_byte(&buffer, type_indicator)?;
        Ok(())
    }

    pub fn check_account_buffer(
        buf: &[u8],
        type_indicator: SwitchboardAccountType,
    ) -> Result<(), ProgramError> {
        AccountType::strip_type_byte(buf, type_indicator)?;
        Ok(())
    }

    pub fn strip_type_byte<'a>(
        buf: &'a [u8],
        type_indicator: SwitchboardAccountType,
    ) -> Result<&'a [u8], ProgramError> {
        if buf[0] != type_indicator as u8 {
            msg!("Account type {:?} != {:?}", buf[0], type_indicator.clone());
            return Err(ProgramError::InvalidAccountData);
        }
        Ok(&buf[1..])
    }

    pub fn set_type_byte(buf: &mut [u8], type_indicator: SwitchboardAccountType) -> Result<(), ProgramError> {
        let type_indicator_byte = type_indicator as u8;
        if buf[0] != SwitchboardAccountType::TYPE_UNINITIALIZED as u8 && buf[0] != type_indicator_byte {
            msg!("Invalid account type change");
            return Err(ProgramError::AccountAlreadyInitialized);
        }
        buf[0] = type_indicator_byte;
        Ok(())
    }
}

pub mod mod_test_utils {
    use super::*;

    pub fn new_account_info<'a>(
        owner: &'a Pubkey,
        key: &'a Pubkey,
        lamports: &'a mut u64,
        data: &'a mut [u8],
    ) -> AccountInfo<'a> {
        AccountInfo::new(
            key,      // key: &'a Pubkey,
            false,    // is_signer: bool,
            true,     // is_writable: bool,
            lamports, // lamports: &'a mut u64,
            data,     // data: &'a mut [u8],
            owner,    // owner: &'a Pubkey,
            false,    // executable: bool,
            100,      // rent_epoch: Epoch
        )
    }

    pub fn create_aggregator() -> AggregatorState {
        AggregatorState {
            version: Some(1),
            configs: Some(mod_AggregatorState::Configs {
                locked: Some(false),
                min_confirmations: Some(0),
                min_update_delay_seconds: Some(0),
                schedule: None,
            }),
            fulfillment_manager_pubkey: Some(Vec::new()),
            job_definition_pubkeys: Vec::new(),
            agreement: None,
            current_round_result: None,
            last_round_result: None,
            parse_optimized_result_address: None,
        }
    }

    pub fn create_fm() -> FulfillmentManagerState {
        FulfillmentManagerState {
            version: Some(1),
            configs: Some(mod_FulfillmentManagerState::Configs {
                heartbeat_auth_required: Some(false),
                usage_auth_required: Some(false),
                locked: Some(false),
            }),
            entries: Vec::new(),
        }
    }

}