3

Say the program is in the middle of executing Instruction 2b.

Instruction 1
Instruction 2
  Instruction 2a
  Instruction 2b
  Instruction 2c
Instruction 3

Is it possible to programmatically figure out that 2b was called by instruction 2?

Context: I want to forbid anyone from calling a specific instruction in my program via CPI.

1 Answer 1

11

Yes! Solana provides an Instructions sysvar. Here's an example.

use anchor_lang::solana_program::sysvar::instructions as tx_instructions;
...

#[account(address = tx_instructions::ID)]
pub instructions: UncheckedAccount<'info>,

...
// Forbid creating voter accounts from CPI.
{
    let ixns = ctx.accounts.instructions.to_account_info();
    let current_index = tx_instructions::load_current_index_checked(&ixns)? as usize;
    let current_ixn = tx_instructions::load_instruction_at_checked(current_index, &ixns)?;
    require_keys_eq!(
        current_ixn.program_id,
        *ctx.program_id,
        VsrError::ForbiddenCpi
    );
}
0

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.