2

Let's say I have an account passed in the instruction

#[account(mut), constraint = optional_ata.mint = treasury_ata.mint]
pub optional_ata: Option<Account<'info, TokenAccount>>

Is this method safe to check if optional_ata was passed in?

// If optional_ata was passed in
if optional_ata.is_some() {....}

IF not, how do I check if optional_ata was passed in or not using if statement?

2 Answers 2

2

The normal Rust rules apply on this account, so using is_some() is a great way to check if it was passed. The more idiomatic Rust construct is to use if let binding, ie:

if let Some(account) = optional_account {
// do stuff with the account
}
0

It's much easier to make the account mandatory and pass the default Pubkey (PublicKey.default) if it is not used. Optional accounts will make it annoying to pass your accounts as arguments.

You might then validate manually instead of with constraints, e.g.:

    if *optional_ata.key() == Pubkey::default() {
        Ok(())
    } else {
        // whatever validate you do for "actual" accounts
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.