-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
76 lines (63 loc) · 1.95 KB
/
lib.rs
File metadata and controls
76 lines (63 loc) · 1.95 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
use anchor_lang::prelude::*;
declare_id!("11111111111111111111111111111111");
#[program]
pub mod missing_mut_constraint {
use super::*;
// Bad: Account (vault) is mutated but not declared with #[account(mut)]
pub fn update_bad(ctx: Context<UpdateBad>) -> Result<()> {
ctx.accounts.vault.amount += 1;
Ok(())
}
// Good: Account (vault) has #[account(mut)]
pub fn update_good(ctx: Context<UpdateGood>) -> Result<()> {
ctx.accounts.vault.amount += 1;
Ok(())
}
// Good: Account (vault) is only read, no mut needed
pub fn read_only(ctx: Context<ReadOnly>) -> Result<()> {
let _ = ctx.accounts.vault.amount;
Ok(())
}
// Bad: Account (treasury) is mutated but not declared with #[account(mut)] (Account (vault) has mut)
pub fn transfer_bad(ctx: Context<TransferBad>) -> Result<()> {
ctx.accounts.vault.amount -= 10;
ctx.accounts.treasury.amount += 10;
Ok(())
}
// Good: lamport mutation with #[account(mut)] on payer
pub fn pay_lamports(ctx: Context<PayLamports>, amount: u64) -> Result<()> {
**ctx.accounts.payer.lamports.borrow_mut() -= amount;
**ctx.accounts.recipient.lamports.borrow_mut() += amount;
Ok(())
}
}
#[account]
pub struct Vault {
pub amount: u64,
}
#[derive(Accounts)]
pub struct UpdateBad<'info> {
pub vault: Account<'info, Vault>, // [missing_mut_constraint]
}
#[derive(Accounts)]
pub struct UpdateGood<'info> {
#[account(mut)]
pub vault: Account<'info, Vault>,
}
#[derive(Accounts)]
pub struct ReadOnly<'info> {
pub vault: Account<'info, Vault>,
}
#[derive(Accounts)]
pub struct TransferBad<'info> {
#[account(mut)]
pub vault: Account<'info, Vault>,
pub treasury: Account<'info, Vault>, // [missing_mut_constraint]
}
#[derive(Accounts)]
pub struct PayLamports<'info> {
#[account(mut)]
pub payer: AccountInfo<'info>,
#[account(mut)]
pub recipient: AccountInfo<'info>,
}