forked from solana-foundation/program-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
90 lines (74 loc) · 2.47 KB
/
Copy pathlib.rs
File metadata and controls
90 lines (74 loc) · 2.47 KB
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
use borsh::{to_vec, BorshDeserialize, BorshSerialize};
#[cfg(not(feature = "no-entrypoint"))]
use solana_program::entrypoint;
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint::ProgramResult,
msg,
program::invoke,
program_error::ProgramError,
pubkey::Pubkey,
rent::Rent,
system_instruction,
sysvar::Sysvar,
};
#[cfg(not(feature = "no-entrypoint"))]
entrypoint!(process_instruction);
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
if let Ok(power_status) = PowerStatus::try_from_slice(instruction_data) {
return initialize(program_id, accounts, power_status);
}
if let Ok(set_power_status) = SetPowerStatus::try_from_slice(instruction_data) {
return switch_power(accounts, set_power_status.name);
}
Err(ProgramError::InvalidInstructionData)
}
pub fn initialize(
program_id: &Pubkey,
accounts: &[AccountInfo],
power_status: PowerStatus,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let power = next_account_info(accounts_iter)?;
let user = next_account_info(accounts_iter)?;
let system_program = next_account_info(accounts_iter)?;
let account_span = (to_vec(&power_status))?.len();
let lamports_required = (Rent::get()?).minimum_balance(account_span);
invoke(
&system_instruction::create_account(
user.key,
power.key,
lamports_required,
account_span as u64,
program_id,
),
&[user.clone(), power.clone(), system_program.clone()],
)?;
power_status.serialize(&mut &mut power.data.borrow_mut()[..])?;
Ok(())
}
pub fn switch_power(accounts: &[AccountInfo], name: String) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let power = next_account_info(accounts_iter)?;
let mut power_status = PowerStatus::try_from_slice(&power.data.borrow())?;
power_status.is_on = !power_status.is_on;
power_status.serialize(&mut &mut power.data.borrow_mut()[..])?;
msg!("{} is pulling the power switch!", &name);
match power_status.is_on {
true => msg!("The power is now on."),
false => msg!("The power is now off!"),
};
Ok(())
}
#[derive(BorshDeserialize, BorshSerialize, Debug)]
pub struct SetPowerStatus {
pub name: String,
}
#[derive(BorshDeserialize, BorshSerialize, Debug)]
pub struct PowerStatus {
pub is_on: bool,
}