๐ Anchor CPI โ Cross-Program Invocation on Solana
A working example of Anchor-based CPI (Cross Program Invocation) โ when one Solana program calls another. This project demonstrates best practices for inter-program communication using the Anchor framework.
This project illustrates how to structure two Solana programs (program-a
and program-b
) where Program A performs a CPI to Program B, and also interacts with System Program (for SOL transfers).
CPI (Cross-Program Invocation) is a critical building block for modular, reusable smart contracts on Solana. This example is ideal for:
- Developers learning advanced Solana development
- Those building protocol layers or modular dApps
- Projects where multiple programs need to coordinate actions
๐ง Stack & Tools
- ๐ฆ Rust โ primary language
- โ Anchor โ Solana framework
- ๐ CPI Pattern
- ๐ Transaction Explorer
- ๐งช Anchor tests with local validator
โจ Features
-
Call Another Program from Your Program
- CPI pattern with
invoke_signed()
in Anchor
- CPI pattern with
-
Pass Accounts & Instruction Data
- Structured instruction building for inner program calls
-
Work with System Program
- Demonstrates how to invoke built-in programs (e.g., SOL transfers)
-
Observe Execution Flow
- View log output to understand program interaction sequence
๐ Setup & Usage
1. ๐๏ธ Initialize Projects
Create two Anchor programs:
anchor init program-a
cd ..
anchor init program-b
2. ๐ Configure Dependencies
In Cargo.toml
of program-a
, add:
program-b = { path = "../program-b", features = ["cpi"] }
In Anchor.toml
of program-a
, disable auto-resolution of dependencies:
[programs.localnet]
program_b = "..." # Your local key
[workspace.dependencies]
program-b = { path = "../program-b", features = ["cpi"], resolution = false }
3. ๐งช Run Tests
Build and test CPI interaction:
anchor build && anchor test
4. ๐งฑ Start Local Validator
cd .anchor/
solana-test-validator
5. ๐ View Transactions
- Open explorer.solana.com
- Switch to "Localhost" network
- Find your transaction signature in test output logs
๐ฅ๏ธ Sample Logs
Program logged: "Instruction: Initialize"
Program logged: "Greetings from: Program A"
Program invoked: System Program
Program returned success
Program invoked: Unknown Program (...)
Program logged: "Instruction: Initialize"
Program logged: "Greetings from: Program B"
Program consumed: 676 of 190087 compute units
Program returned success
These logs show:
- Instruction flow through both programs
- System-level interaction
- Success/failure of each step
๐ License
This project is licensed under the MIT License โ free to use, modify, and extend.