Skip to content

chefburger/cpi-error-handle-demo

Repository files navigation

Solana CPI Error Handling POC

Note: the doc is generated by AI

This repository demonstrates a critical limitation in Solana programs: Cross-Program Invocation (CPI) errors cannot be recovered from. When a CPI call fails, the entire transaction is reverted, and there's no way to catch or handle the error within the calling program.

What This Demonstrates

1. System CPI Error Handling

The test_system_cpi instruction attempts to transfer tokens with insufficient funds:

// This should fail with insufficient funds
let transfer_result = token::transfer(transfer_ctx, 2);

msg!("CODE DIDNT REACH HERE ????"); // This line never executes!

match transfer_result {
    Ok(_) => { /* Never reached */ },
    Err(_err) => { /* Never reached */ }
}

Result: The msg!("CODE DIDNT REACH HERE ????") line never executes because the transaction reverts immediately when the CPI fails.

2. Custom Program CPI Error Handling

The test_custom_cpi instruction calls a program that always fails:

// This should always fail
let cpi_result = always_fail(cpi_ctx);

msg!("CODE DIDNT REACH HERE ????") // This line never executes!

match cpi_result {
    Ok(_) => { /* Never reached */ },
    Err(_err) => { /* Never reached */ }
}

Result: Same behavior - the transaction reverts immediately, and no error handling code executes.

Setup

# Install dependencies
npm install

# Build the programs
anchor build

# Run tests
anchor test

Expected Test Output

Both tests will fail with errors, demonstrating that:

  1. The CPI calls fail as expected
  2. No code after the failed CPI call executes
  3. The entire transaction reverts

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors