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
use solana_program::{
account_info::AccountInfo,
entrypoint::ProgramResult,
program::{invoke, invoke_signed},
pubkey::Pubkey,
rent::Rent,
system_instruction,
};
pub fn create_pda_account<'a>(
payer: &AccountInfo<'a>,
rent: &Rent,
space: usize,
owner: &Pubkey,
system_program: &AccountInfo<'a>,
new_pda_account: &AccountInfo<'a>,
new_pda_signer_seeds: &[&[u8]],
) -> ProgramResult {
if new_pda_account.lamports() > 0 {
let required_lamports = rent
.minimum_balance(space)
.max(1)
.saturating_sub(new_pda_account.lamports());
if required_lamports > 0 {
invoke(
&system_instruction::transfer(payer.key, new_pda_account.key, required_lamports),
&[
payer.clone(),
new_pda_account.clone(),
system_program.clone(),
],
)?;
}
invoke_signed(
&system_instruction::allocate(new_pda_account.key, space as u64),
&[new_pda_account.clone(), system_program.clone()],
&[new_pda_signer_seeds],
)?;
invoke_signed(
&system_instruction::assign(new_pda_account.key, owner),
&[new_pda_account.clone(), system_program.clone()],
&[new_pda_signer_seeds],
)
} else {
invoke_signed(
&system_instruction::create_account(
payer.key,
new_pda_account.key,
rent.minimum_balance(space).max(1),
space as u64,
owner,
),
&[
payer.clone(),
new_pda_account.clone(),
system_program.clone(),
],
&[new_pda_signer_seeds],
)
}
}