rathe_storage_program/
state.rs1use borsh::{BorshDeserialize, BorshSerialize};
2use solana_program::{
3 account_info::AccountInfo,
4 pubkey::{Pubkey, PubkeyError},
5};
6use solana_program::{program_error::ProgramError, program_memory::sol_memset};
7
8use crate::error::StorageError;
9
10#[derive(BorshSerialize, BorshDeserialize, Debug)]
11pub struct Storage {
12 pub owner: Pubkey,
13 pub is_initialized: bool,
14 pub value: i32,
15}
16
17impl Storage {
18 pub const LEN: usize = 32 + 1 + 4;
19 pub const SEED: &'static str = "STORAGE";
20
21 pub(crate) fn initialize(&mut self, owner: &Pubkey, value: i32) -> &mut Self {
23 self.owner = *owner;
24 self.is_initialized = true;
25 self.value = value;
26 self
27 }
28
29 pub(crate) fn update_value(&mut self, value: i32) -> &mut Self {
31 self.value = value;
32 self
33 }
34
35 pub(crate) fn try_from_account_info(account: &AccountInfo) -> Result<Self, ProgramError> {
37 Self::try_from_slice(&account.data.borrow()).map_err(ProgramError::from)
38 }
39
40 pub(crate) fn try_save_to_account_info(
42 &self,
43 storage_account: &AccountInfo,
44 ) -> Result<(), ProgramError> {
45 self.serialize(&mut *storage_account.data.borrow_mut())
46 .map_err(ProgramError::from)
47 }
48
49 pub(crate) fn destroy(&mut self, storage_account: &AccountInfo) {
50 sol_memset(*storage_account.data.borrow_mut(), 0u8, Storage::LEN)
51 }
52
53 pub(crate) fn spoil(&mut self) -> Result<(), StorageError> {
54 Err(StorageError::InvalidOperation)
55 }
56
57 pub fn generate_id(owner: &Pubkey) -> Result<Pubkey, PubkeyError> {
58 Pubkey::create_with_seed(owner, Self::SEED, &crate::id())
59 }
60}