Solana CPI and composition: what programs call what
Cross-program invocation is the feature that makes Solana programmable money
instead of programmable islands. It lets one program call another mid-
transaction, so a swap can route through three exchanges, a loan can move
collateral between protocols, and an aggregator can compose things nobody
anticipated. It is also where a class of subtle bugs lives.
What CPI actually does
When program A invokes program B, B executes with A's transaction context:
the same signer, the same accounts passed in, the same fee payer. B sees the
accounts A gave it and can only touch what A authorized. There is no hidden
authority leaking between calls - the security model is deliberately boring,
and that is a feature.
Composition chains look like this:
- A DEX aggregator calls several AMMs in one transaction and stitches the
best route.
- A lending protocol moves collateral: withdraw from one pool, deposit into
another, all inside one atomic transaction.
- A payment router calls a token program, an exchange program, and a staking
program to turn a deposit into a yield position in one signature.
The limits that bite
- Depth. CPI nesting is capped, and the cap has been tightened over time
because deep call stacks burn compute and complicate failure handling.
Check the current runtime docs; assume less headroom than you remember.
- Compute budget. Every CPI call costs compute units. A composition that
looks free in theory runs out of budget in practice, and the transaction
dies mid-chain with an error that names the outer program, not the culprit.
- Account ownership. A program can only write accounts it owns. Invoking a
program that expects to own an account it does not own is a classic
first-week failure.
The discipline that keeps it safe
- Pass the minimum accounts. Every extra writable account is attack surface
and compute.
- Validate inputs from the caller, not just from your own logic. CPI means
strangers reach into your state through someone else's front door.
- Test the failure path. If an inner call reverts, does the outer state stay
consistent? Write that test before mainnet.
The takeaway
Treat CPI as a power tool: compose aggressively, pass minimal authority,
budget compute for the worst realistic chain, and test reverts end to end.
The protocols that ship reliable compositions are the ones that treat the
call graph as part of the threat model.