solana_config_program/
date_instruction.rs

1///
2/// A library for creating a trusted date oracle.
3///
4use bincode::{deserialize, serialized_size};
5use {
6    crate::{config_instruction, ConfigState},
7    chrono::{
8        prelude::{DateTime, TimeZone, Utc},
9        serde::ts_seconds,
10    },
11    serde_derive::{Deserialize, Serialize},
12    solana_instruction::Instruction,
13    solana_pubkey::Pubkey,
14};
15
16#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
17pub struct DateConfig {
18    #[serde(with = "ts_seconds")]
19    pub date_time: DateTime<Utc>,
20}
21
22impl Default for DateConfig {
23    fn default() -> Self {
24        Self {
25            date_time: Utc.timestamp_opt(0, 0).unwrap(),
26        }
27    }
28}
29impl DateConfig {
30    pub fn new(date_time: DateTime<Utc>) -> Self {
31        Self { date_time }
32    }
33
34    pub fn deserialize(input: &[u8]) -> Option<Self> {
35        deserialize(input).ok()
36    }
37}
38
39impl ConfigState for DateConfig {
40    fn max_space() -> u64 {
41        serialized_size(&Self::default()).unwrap()
42    }
43}
44
45/// Create a date account. The date is set to the Unix epoch.
46pub fn create_account(
47    payer_pubkey: &Pubkey,
48    date_pubkey: &Pubkey,
49    lamports: u64,
50) -> Vec<Instruction> {
51    config_instruction::create_account::<DateConfig>(payer_pubkey, date_pubkey, lamports, vec![])
52}
53
54/// Set the date in the date account. The account pubkey must be signed in the
55/// transaction containing this instruction.
56pub fn store(date_pubkey: &Pubkey, date_time: DateTime<Utc>) -> Instruction {
57    let date_config = DateConfig::new(date_time);
58    config_instruction::store(date_pubkey, true, vec![], &date_config)
59}