How to detect if a Solana program is invoked via CPI?

Viewed 160

A Solana program can be invoked by user or another program via CPI (cross program invocation), how to detect this in the context of the invoked program.

1 Answers

There's no way to do this totally dynamically at the moment, but if you have access to the Instructions sysvar (https://docs.solana.com/developing/runtime-facilities/sysvars#instructions), you can do:

let instruction = solana_program::sysvar::instructions::get_instruction_relative(
        0, sysvar_instructions_account_info
    ).unwrap();
if instruction.program_id == my_program_id {
    // not CPI
} else {
    // CPI
}

Full source code at: https://github.com/solana-labs/solana/blob/79a8ecd0ac3b31ed25fa355fdb77b2c535347f78/sdk/program/src/sysvar/instructions.rs#L209

Related