Skip to content

Commit

Permalink
utils: Log assert failures for easier debugging
Browse files Browse the repository at this point in the history
  • Loading branch information
KartikSoneji committed Nov 11, 2023
1 parent d49ff0a commit b73834d
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions core/rust/utils/src/assertions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use solana_program::{
account_info::AccountInfo,
entrypoint::ProgramResult,
log::sol_log,
program_error::ProgramError,
program_pack::{IsInitialized, Pack},
pubkey::Pubkey,
Expand All @@ -9,6 +10,13 @@ use solana_program::{

pub fn assert_signer(account_info: &AccountInfo) -> ProgramResult {
if !account_info.is_signer {
sol_log(
format!(
"signer assertion failed for {key}: not signer",
key = account_info.key,
)
.as_str(),
);
Err(ProgramError::MissingRequiredSignature)
} else {
Ok(())
Expand All @@ -21,6 +29,13 @@ pub fn assert_initialized<T: Pack + IsInitialized>(
) -> Result<T, ProgramError> {
let account: T = T::unpack_unchecked(&account_info.data.borrow())?;
if !account.is_initialized() {
sol_log(
format!(
"initialized assertion failed for {key}: not initialized",
key = account_info.key,
)
.as_str(),
);
Err(error.into())
} else {
Ok(account)
Expand All @@ -33,6 +48,15 @@ pub fn assert_owned_by(
error: impl Into<ProgramError>,
) -> ProgramResult {
if account.owner != owner {
sol_log(
format!(
"owner assertion failed for {key}: expected {expected}, got {actual}",
key = account.key,
expected = owner,
actual = account.owner
)
.as_str(),
);
Err(error.into())
} else {
Ok(())
Expand All @@ -47,6 +71,17 @@ pub fn assert_derivation(
) -> Result<u8, ProgramError> {
let (key, bump) = Pubkey::find_program_address(path, program_id);
if key != *account.key {
sol_log(
format!(
"derivation assertion failed for {actual_key}:\n
\x20 expected {key} with program {program_id}, path {path:?}",
actual_key = account.key,
key = key,
program_id = program_id,
path = path,
)
.as_str(),
);
return Err(error.into());
}
Ok(bump)
Expand All @@ -58,6 +93,15 @@ pub fn assert_rent_exempt(
error: impl Into<ProgramError>,
) -> ProgramResult {
if !rent.is_exempt(account_info.lamports(), account_info.data_len()) {
sol_log(
format!(
"rent exempt assertion failed for {key}: has {balance} lamports, requires at least {min} lamports",
key = account_info.key,
balance = account_info.lamports(),
min = rent.minimum_balance(account_info.data_len()),
)
.as_str(),
);
Err(error.into())
} else {
Ok(())
Expand Down

0 comments on commit b73834d

Please sign in to comment.