Skip to content

Commit 2594fb8

Browse files
authored
Adds extra assertions (#90)
* feat: adds extra assertions * chore: adds changeset * chore: cleaning up changeset
1 parent d4c2ac0 commit 2594fb8

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

.changeset/lovely-gorillas-invite.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"create-solana-program": patch
3+
---
4+
5+
Adds extra assertion helpers for shank programs

template/shank/base/program/src/assertions.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,26 @@ use solana_program::{
44
pubkey::Pubkey,
55
};
66

7+
/// Assert that the given account is owned by the given program or one of the given owners.
8+
/// Useful for dealing with program interfaces.
9+
pub fn assert_program_owner_either(
10+
account_name: &str,
11+
account: &AccountInfo,
12+
owners: &[Pubkey],
13+
) -> ProgramResult {
14+
if !owners.iter().any(|owner| account.owner == owner) {
15+
msg!(
16+
"Account \"{}\" [{}] must be owned by either {:?}",
17+
account_name,
18+
account.key,
19+
owners
20+
);
21+
Err(CounterError::InvalidProgramOwner.into())
22+
} else {
23+
Ok(())
24+
}
25+
}
26+
727
/// Assert that the given account is owned by the given program.
828
pub fn assert_program_owner(
929
account_name: &str,
@@ -44,6 +64,27 @@ pub fn assert_pda(
4464
Ok(bump)
4565
}
4666

67+
/// Assert the derivation of the seeds plus bump against the given account.
68+
pub fn assert_pda_with_bump(
69+
account_name: &str,
70+
account: &AccountInfo,
71+
program_id: &Pubkey,
72+
seeds_with_bump: &[&[u8]],
73+
) -> ProgramResult {
74+
let key = Pubkey::create_program_address(seeds_with_bump, program_id)?;
75+
if *account.key != key {
76+
msg!(
77+
"Account \"{}\" [{}] is an invalid PDA. Expected the following valid PDA [{}]",
78+
account_name,
79+
account.key,
80+
key,
81+
);
82+
Err(CounterError::InvalidPda.into())
83+
} else {
84+
Ok(())
85+
}
86+
}
87+
4788
/// Assert that the given account is empty.
4889
pub fn assert_empty(account_name: &str, account: &AccountInfo) -> ProgramResult {
4990
if !account.data_is_empty() {

0 commit comments

Comments
 (0)