CPI to the System Program
The System Program handles account creation, assignment, allocation, and lamport transfers. Most programs CPI to it for rent payment and SOL movement.
Recipe
invoke(
&system_instruction::transfer(from.key, to.key, amount),
&[from.clone(), to.clone()],
)?;When to reach for this:
- Paying rent for new accounts.
- Moving SOL to treasury or users.
- Closing accounts and returning rent.
Working Example
let rent = Rent::get()?;
let lamports = rent.minimum_balance(space);
invoke(
&system_instruction::create_account(payer.key, new.key, lamports, space as u64, owner),
&[payer.clone(), new.clone(), system_program.clone()],
)?;What this demonstrates:
- Rent sysvar for minimum balance.
- create_account sets owner program.
- Payer signs transfer/create.
Deep Dive
Common Instructions
| IX | Purpose |
|---|---|
| transfer | Move lamports |
| create_account | Allocate + assign |
| allocate | Add space |
| assign | Change owner (restricted) |
Rust Notes
use solana_program::system_program;Gotchas
- Transfer from PDA without signed - Fails.. Fix: invoke_signed.
- Create on existing - Fails if lamports > 0.. Fix: Check empty account.
- Insufficient lamports - Transfer/create fails.. Fix: Balance checks.
- Wrong owner param - Account stuck wrong owner.. Fix: Pass your program id.
- Rent not exempt - Account deallocated.. Fix: Fund minimum_balance.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| Client creates account | Simpler program | PDA flows |
| Anchor init | Abstracts | Native |
| transfer_with_seed | Derived addresses | PDA preferred |
FAQs
System program id?
11111111111111111111111111111111
Create + init same tx?
Yes.
Close account?
Transfer all lamports out.
Assign CPI?
Rare - security sensitive.
allocate vs create?
create for new keys.
PDA create?
invoke_signed.
Rent sysvar?
Rent::get() in program.
Zero lamports transfer?
Allowed but pointless.
Signer for transfer?
From account signer.
Multi transfer?
Multiple CPIs ok.
Agave 4.1.1?
Match system_instruction helpers.
Surfpool?
Test rent math.
Related
- Creating Accounts via CPI - Patterns
- Vault & Escrow - Custody
- Fee & Treasury Patterns - Fees
Stack versions: This page was written for Agave 4.1.1, Solana CLI 3.0.10, Anchor 0.32.1, anchor-lang 0.32.1, Rust 1.91.1, @solana/kit 7.0.0, Surfpool 0.12.0, and LiteSVM 0.6.x.