-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathtop_up_ephemeral_balance.rs
More file actions
87 lines (79 loc) · 2.47 KB
/
top_up_ephemeral_balance.rs
File metadata and controls
87 lines (79 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
use borsh::BorshDeserialize;
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program::invoke,
program_error::ProgramError, pubkey::Pubkey, system_instruction::transfer,
system_program,
};
use crate::{
args::TopUpEphemeralBalanceArgs,
ephemeral_balance_seeds_from_payer,
processor::utils::{
loaders::{load_pda, load_program, load_signer},
pda::create_pda,
},
};
/// Tops up the ephemeral balance account.
///
/// Accounts:
///
/// 0: `[writable]` payer account who funds the topup
/// 1: `[]` pubkey account that the ephemeral balance PDA was derived from
/// 2: `[writable]` ephemeral balance account to top up
/// 3: `[]` system program
///
/// Requirements:
///
/// - the payer account has enough lamports to fund the transfer
///
/// Steps:
///
/// 1. Create the ephemeral balance PDA if it does not exist
/// 2. Transfer lamports from payer to ephemeral PDA
pub fn process_top_up_ephemeral_balance(
_program_id: &Pubkey,
accounts: &[AccountInfo],
data: &[u8],
) -> ProgramResult {
// Parse args.
let args = TopUpEphemeralBalanceArgs::try_from_slice(data)?;
// Load Accounts
let [payer, pubkey, ephemeral_balance_account, system_program] = accounts
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(payer, "payer")?;
load_program(system_program, system_program::id(), "system program")?;
let bump_ephemeral_balance = load_pda(
ephemeral_balance_account,
ephemeral_balance_seeds_from_payer!(pubkey.key, args.index),
&crate::id(),
true,
"ephemeral balance",
)?;
// Create the ephemeral balance PDA if it does not exist
if ephemeral_balance_account.owner.eq(&system_program::id()) {
create_pda(
ephemeral_balance_account,
&system_program::id(),
0,
ephemeral_balance_seeds_from_payer!(pubkey.key, args.index),
bump_ephemeral_balance,
system_program,
payer,
)?;
}
// Transfer lamports from payer to ephemeral PDA (with a system program call)
if args.amount > 0 {
let transfer_instruction =
transfer(payer.key, ephemeral_balance_account.key, args.amount);
invoke(
&transfer_instruction,
&[
payer.clone(),
ephemeral_balance_account.clone(),
system_program.clone(),
],
)?;
}
Ok(())
}