-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwithdraw_secure.rs
More file actions
57 lines (47 loc) · 1.6 KB
/
Copy pathwithdraw_secure.rs
File metadata and controls
57 lines (47 loc) · 1.6 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
use anchor_lang::prelude::*;
use crate::state::Vault;
/// Withdraw lamports from vault - SECURE version
///
/// ✅ SECURE: This instruction checks that the remaining balance
/// stays above the rent-exempt minimum before allowing withdrawal.
#[derive(Accounts)]
pub struct WithdrawSecure<'info> {
#[account(
mut,
seeds = [b"vault", owner.key().as_ref()],
bump = vault.bump,
has_one = owner
)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub owner: Signer<'info>,
}
pub fn handler(ctx: Context<WithdrawSecure>, amount: u64) -> Result<()> {
let vault = &ctx.accounts.vault;
let vault_info = vault.to_account_info();
// Get current balance
let vault_balance = vault_info.lamports();
// ✅ SECURE: Calculate rent-exempt minimum for this account
let rent = Rent::get()?;
let rent_exempt_minimum = rent.minimum_balance(vault_info.data_len());
// ✅ SECURE: Calculate maximum withdrawable amount
let max_withdrawable = vault_balance
.checked_sub(rent_exempt_minimum)
.unwrap_or(0);
// ✅ SECURE: Check that withdrawal won't violate rent exemption
require!(
amount <= max_withdrawable,
crate::error::ErrorCode::WouldViolateRentExemption
);
// Safe to transfer
**vault_info.try_borrow_mut_lamports()? -= amount;
**ctx.accounts.owner.try_borrow_mut_lamports()? += amount;
let remaining = vault_info.lamports();
msg!(
"SECURE: Withdrew {} lamports. Remaining: {} (rent-exempt min: {})",
amount,
remaining,
rent_exempt_minimum
);
Ok(())
}