Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add comments to 6-duplicate-mutable-accounts #44

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions programs/6-duplicate-mutable-accounts/insecure/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@ pub mod duplicate_mutable_accounts_insecure {
use super::*;

pub fn update(ctx: Context<Update>, a: u64, b: u64) -> ProgramResult {
// Accessing both user_a and user_b accounts without any validation
// This could allow a user to pass the same account twice
let user_a = &mut ctx.accounts.user_a;
let user_b = &mut ctx.accounts.user_b;

// Setting the data fields of both accounts
user_a.data = a;
user_b.data = b;
Ok(())
Expand All @@ -18,6 +21,7 @@ pub mod duplicate_mutable_accounts_insecure {

#[derive(Accounts)]
pub struct Update<'info> {
// No checks or constraints on user_a and user_b
user_a: Account<'info, User>,
user_b: Account<'info, User>,
}
Expand Down
2 changes: 2 additions & 0 deletions programs/6-duplicate-mutable-accounts/recommended/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod duplicate_mutable_accounts_recommended {
let user_a = &mut ctx.accounts.user_a;
let user_b = &mut ctx.accounts.user_b;

// Updating the data fields of both accounts
user_a.data = a;
user_b.data = b;
Ok(())
Expand All @@ -18,6 +19,7 @@ pub mod duplicate_mutable_accounts_recommended {

#[derive(Accounts)]
pub struct Update<'info> {
// Constraint ensures that user_a and user_b are different accounts
#[account(constraint = user_a.key() != user_b.key())]
user_a: Account<'info, User>,
user_b: Account<'info, User>,
Expand Down
5 changes: 4 additions & 1 deletion programs/6-duplicate-mutable-accounts/secure/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ pub mod duplicate_mutable_accounts_secure {
use super::*;

pub fn update(ctx: Context<Update>, a: u64, b: u64) -> ProgramResult {
// Check at runtime to ensure that user_a and user_b are different accounts
if ctx.accounts.user_a.key() == ctx.accounts.user_b.key() {
return Err(ProgramError::InvalidArgument)
return Err(ProgramError::InvalidArgument);
}

let user_a = &mut ctx.accounts.user_a;
let user_b = &mut ctx.accounts.user_b;

// Safely update the data fields of both accounts
user_a.data = a;
user_b.data = b;
Ok(())
Expand Down