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