-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclaim_secure.rs
More file actions
60 lines (51 loc) · 1.73 KB
/
Copy pathclaim_secure.rs
File metadata and controls
60 lines (51 loc) · 1.73 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
use anchor_lang::prelude::*;
use crate::state::{RewardConfig, UserReward};
/// Claim rewards - handles existing or new account
///
/// ✅ SECURE: Uses `init_if_needed` constraint for user_reward account.
/// This handles BOTH cases:
/// - If account doesn't exist: creates it
/// - If account already exists: uses existing one
///
/// Front-running attack is neutralized because the instruction
/// succeeds regardless of whether the account exists.
#[derive(Accounts)]
pub struct ClaimSecure<'info> {
#[account(
seeds = [b"config"],
bump = config.bump
)]
pub config: Account<'info, RewardConfig>,
/// ✅ SECURE: Using `init_if_needed` handles both cases!
/// - Account doesn't exist? Create it.
/// - Account already exists? Use it.
/// Front-running attack is neutralized.
#[account(
init_if_needed,
payer = user,
space = UserReward::LEN,
seeds = [b"user_reward", config.key().as_ref(), user.key().as_ref()],
bump
)]
pub user_reward: Account<'info, UserReward>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
pub fn handler(ctx: Context<ClaimSecure>) -> Result<()> {
let user_reward = &mut ctx.accounts.user_reward;
// Check if already claimed (account might have existed)
if user_reward.claimed {
msg!("User has already claimed rewards");
return Ok(());
}
user_reward.user = ctx.accounts.user.key();
user_reward.config = ctx.accounts.config.key();
user_reward.claimed = true;
user_reward.bump = ctx.bumps.user_reward;
msg!(
"SECURE: Claimed {} tokens (account created or already existed)",
ctx.accounts.config.reward_amount
);
Ok(())
}