Anchor CPI: Cross-Program Invocation on Solana
Two Anchor programs where one calls the other through a CPI, with a System Program transfer alongside it.
A working example of Anchor-based CPI, where one Solana program calls another.
The project has two Solana programs, program-a and program-b. Program A performs a CPI to Program B, and also interacts with the System Program for SOL transfers.
CPI is a building block for modular, reusable smart contracts on Solana. The example suits:
- Developers learning advanced Solana development
- Those building protocol layers or modular dApps
- Projects where multiple programs need to coordinate actions
Stack and tools
- Rust, the primary language
- Anchor, the Solana framework
- CPI pattern
- Transaction explorer
- Anchor tests with a local validator
Features
- Call another program from your program. The CPI pattern with
invoke_signed()in Anchor. - Pass accounts and instruction data. Structured instruction building for inner program calls.
- Work with the System Program. Shows how to invoke built-in programs, for example SOL transfers.
- Observe the execution flow. The log output shows the sequence of program interactions.
Setup and usage
- Initialize the projects:
anchor init program-a
cd ..
anchor init program-b
- Configure the dependencies. In
Cargo.tomlofprogram-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 }
- Run the tests:
anchor build && anchor test
- Start the local validator:
cd .anchor/
solana-test-validator
-
View the transactions:
-
Open explorer.solana.com
-
Switch to the “Localhost” network
-
Find your transaction signature in the 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
The logs show the instruction flow through both programs, the System-level interaction, and the success or failure of each step.
License
This project is licensed under the MIT License. Free to use, modify, and extend.
Neighbors in time
Related: the posts that share this one's subject, and where the thread goes next.