Rules › Anchor (Rust)
init_if_needed (reinitialization risk)
init_if_needed accepts accounts that already exist; without checks an attacker can reset or reuse state.
Why it matters
init_if_needed creates the account if it doesn't exist and otherwise accepts the existing one. That makes it easy to write an instruction that can be called again to reset state, or that accepts an account initialized by someone else with different parameters. Anchor gates it behind a feature flag for this reason. Prefer a separate init instruction, or check the account's state explicitly.
Vulnerable
#[account(init_if_needed, payer = user, space = 8 + Vault::INIT_SPACE)]
pub vault: Account<'info, Vault>,
Fixed
#[account(init, payer = user, space = 8 + Vault::INIT_SPACE, seeds = [b"vault", user.key().as_ref()], bump)]
pub vault: Account<'info, Vault>,
What other tools call it
| Tool | Detector or reference |
|---|---|
| Anchor | requires the init-if-needed feature |
| Sealevel attacks | 4-initialization |
Check your code
Paste a contract into the in-browser checker, or let the Claude Code plugin scan before every deploy. The quick check for this rule is a pattern match: treat a hit as "look here", and a miss as no guarantee.
Related rules
- Unchecked account without a /// CHECK: note
- Authority account that isn't a Signer
- CPI to a program the caller chooses
- Account data deserialized without an owner check
- Account closed by draining lamports by hand
- overflow-checks not enabled for release builds
Static analysis finds known bug classes; it can't prove code is safe and isn't an audit. Get a professional audit before deploying code that will hold value.