Compute Exhaustion Remediation
How to fix compute unit budget exhaustion issues.
Compute Exhaustion Remediation
Overview
Related Detector: Compute Exhaustion
CPI calls in loops and infinite loops exhaust Solana’s compute budget. The fix is to remove CPI from loops by processing one item per transaction, or to use batched processing with strict upper bounds.
Recommended Fix
Before (Vulnerable)
// Vulnerable: CPI call per loop iteration
for position in positions.iter() {
invoke_signed(&settle_ix, accounts, &[&seeds])?;
}
After (Fixed)
// Fixed: process one per call, use client-side batching
pub fn settle_single(ctx: Context<Settle>, index: u32) -> Result<()> {
let position = &ctx.accounts.state.positions[index as usize];
settle_position(ctx.accounts, position)?;
Ok(())
}
Alternative Mitigations
Compute Budget Request
For operations that genuinely need more compute, request additional units from the client:
// Client-side: request more compute units
const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
units: 400_000,
});
This is a mitigation, not a fix. The program should still bound its compute usage.
Common Mistakes
Mistake: Assuming Default Budget Is Sufficient
// WRONG: assumes 200K compute units is enough for 20 iterations
for i in 0..items.len() {
process_with_cpi(items[i])?; // ~50K CU per CPI call
}
Always calculate worst-case compute consumption and set appropriate bounds.