Skip to content

Commit

Permalink
Adds extra assertions (#90)
Browse files Browse the repository at this point in the history
* feat: adds extra assertions

* chore: adds changeset

* chore: cleaning up changeset
  • Loading branch information
0xC0A1 authored Oct 7, 2024
1 parent d4c2ac0 commit 2594fb8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/lovely-gorillas-invite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-solana-program": patch
---

Adds extra assertion helpers for shank programs
41 changes: 41 additions & 0 deletions template/shank/base/program/src/assertions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,26 @@ use solana_program::{
pubkey::Pubkey,
};

/// Assert that the given account is owned by the given program or one of the given owners.
/// Useful for dealing with program interfaces.
pub fn assert_program_owner_either(
account_name: &str,
account: &AccountInfo,
owners: &[Pubkey],
) -> ProgramResult {
if !owners.iter().any(|owner| account.owner == owner) {
msg!(
"Account \"{}\" [{}] must be owned by either {:?}",
account_name,
account.key,
owners
);
Err(CounterError::InvalidProgramOwner.into())
} else {
Ok(())
}
}

/// Assert that the given account is owned by the given program.
pub fn assert_program_owner(
account_name: &str,
Expand Down Expand Up @@ -44,6 +64,27 @@ pub fn assert_pda(
Ok(bump)
}

/// Assert the derivation of the seeds plus bump against the given account.
pub fn assert_pda_with_bump(
account_name: &str,
account: &AccountInfo,
program_id: &Pubkey,
seeds_with_bump: &[&[u8]],
) -> ProgramResult {
let key = Pubkey::create_program_address(seeds_with_bump, program_id)?;
if *account.key != key {
msg!(
"Account \"{}\" [{}] is an invalid PDA. Expected the following valid PDA [{}]",
account_name,
account.key,
key,
);
Err(CounterError::InvalidPda.into())
} else {
Ok(())
}
}

/// Assert that the given account is empty.
pub fn assert_empty(account_name: &str, account: &AccountInfo) -> ProgramResult {
if !account.data_is_empty() {
Expand Down

0 comments on commit 2594fb8

Please sign in to comment.