macro_rules! require {
    ($invariant:expr, $error:tt $(,)?) => { ... };
    ($invariant:expr, $error:expr $(,)?) => { ... };
}
Expand description

Ensures a condition is true, otherwise returns with the given error. Use this with or without a custom error type.

Example

// Instruction function
pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
    require!(ctx.accounts.data.mutation_allowed, MyError::MutationForbidden);
    ctx.accounts.data.data = data;
    Ok(())
}

// An enum for custom error codes
#[error_code]
pub enum MyError {
    MutationForbidden
}

// An account definition
#[account]
#[derive(Default)]
pub struct MyData {
    mutation_allowed: bool,
    data: u64
}

// An account validation struct
#[derive(Accounts)]
pub struct SetData<'info> {
    #[account(mut)]
    pub data: Account<'info, MyData>
}