Cross-Program Invocation
Cross-Program Invocation (CPI) is the core of the "composability" of BBAChain, allowing programs to "call" each other.
Overview
Cross-Program Invocation allows one program to invoke instructions on another program, enabling programs to build on top of each other and create complex applications.
How CPI Works
When a program invokes another program:
- The calling program creates an instruction for the target program
- The instruction is executed in the context of the calling program
- The target program processes the instruction
- Control returns to the calling program
CPI Example
use bbachain_program::{
account_info::{next_account_info, AccountInfo},
entrypoint::ProgramResult,
program::invoke,
pubkey::Pubkey,
};
pub fn transfer_tokens(
accounts: &[AccountInfo],
amount: u64,
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let source = next_account_info(account_info_iter)?;
let destination = next_account_info(account_info_iter)?;
let authority = next_account_info(account_info_iter)?;
let token_program = next_account_info(account_info_iter)?;
let instruction = bbachain_token::instruction::transfer(
&bbachain_token::id(),
source.key,
destination.key,
authority.key,
&[],
amount,
)?;
invoke(
&instruction,
&[
source.clone(),
destination.clone(),
authority.clone(),
token_program.clone(),
],
)
}
CPI Benefits
- Composability: Programs can build on top of each other
- Reusability: Common functionality can be shared across programs
- Modularity: Complex applications can be broken down into smaller programs
CPI Security
When a program invokes another program via CPI:
- The calling program's privileges are passed to the invoked program
- The invoked program can only modify accounts that the calling program has permission to modify
- The invoked program cannot access accounts that weren't passed to it
Next Steps
- Learn about Transactions
- Understand Accounts
- Explore Programs