Index of every page on this site: llms.txt
All skills
princedotrs avatar

/solana-program-audit

@586e19e
Run it yourself

Security audit of Solana on-chain programs in Rust: Anchor, native solana-program and Pinocchio. Use to audit or review a Solana program, PR or fix and to find vulnerabilities: missing signer or owner checks, account validation, type cosplay, reinitialization, init front-running, closed-account revival, duplicate accounts, PDA seeds and bumps, arbitrary CPI, CPI return data, remaining_accounts, sysvar and instruction introspection, overflow, rounding, Token-2022 extensions and transfer hooks, oracle, flash-loan and MEV attacks, upgrade authority and governance. Covers DeFi reviews (AMM, lending, perps, staking, bridges, launchpads), PoC exploits, fix patches, re-audits, spec compliance, audit readiness, release gates and audit reports. Trigger on code using anchor_lang, solana_program, pinocchio, #[program], #[derive(Accounts)] or entrypoint!. Not for writing features, off-chain clients or backends, EVM/Solidity, or incident response.

  • 237 files
  • 2 MB
  • Updated 4 weeks ago
  • GitHub
Use this Skill: https://skilld.dev/gh/princedotrs/solana-audit/solana-program-audit

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

checklists05-program-state-machine.md

≈6.2k tokens on demand. Your agent reads this file only when SKILL.md points to it.

05 — State Machine & Lifecycle Checklist

Domain: On-chain Solana Program
Severity if missed: HIGH to MEDIUM
References: QEDGen SM properties, Withdrawal lifecycle, Fund lifecycle

Every item below is a single verification step. Mark each [PASS], [FAIL-{severity}], [PARTIAL], or [N/A].


5.1 — State Enum Completeness

  • SM-001: List every state enum in the program (e.g., status enums for withdrawals, funds, positions, etc.)
  • SM-002: For each enum, list ALL variants
  • SM-003: For each enum variant, verify there is at least ONE instruction that transitions INTO that variant
  • SM-004: For each enum variant, verify there is at least ONE instruction that transitions OUT of that variant (unless it's a terminal state)
  • SM-005: Identify dead variants — enum values that are never set by any instruction. Flag as LOW (dead code)
  • SM-006: Dead variants cannot be set via manual data manipulation (Anchor discriminator prevents external writes)
  • SM-007: Terminal states are clearly identified (e.g., "Completed" after withdrawal finalization)
  • SM-008: Terminal state accounts are closed (freed/rent returned) — not left as zombie accounts

5.2 — Withdrawal Lifecycle

Adapt instruction names below to your program's actual withdrawal flow (e.g., initiate_withdrawal, finalize_withdrawal, etc.)

  • SM-009: Withdrawal initiation instruction — sets status to Initiated from no-state (account creation)
  • SM-010: Withdrawal initiation — requires investor signer and position with sufficient shares
  • SM-011: Withdrawal swap/conversion instruction — is it restricted to Initiated status only? Or also allows later states?
  • SM-012: If swap/conversion allows multiple statuses — is that intentional and safe?
  • SM-013: Intermediate readiness instruction — transitions from Initiated to ReadyToFinalize (or equivalent). Does this instruction exist?
  • SM-014: If readiness instruction is MISSING — flag as CRITICAL (broken withdrawal flow)
  • SM-015: Withdrawal finalization — requires intermediate status (not Initiated)
  • SM-016: Withdrawal finalization — closes the withdrawal account (returns rent to investor)
  • SM-017: Withdrawal finalization — burns shares, transfers tokens/SOL to investor
  • SM-018: Withdrawal cancellation — only valid from Initiated status (not ReadyToFinalize)
  • SM-019: Withdrawal cancellation — restores investor's shares / position correctly
  • SM-020: Withdrawal cancellation — closes the withdrawal account
  • SM-021: Can an investor have multiple active withdrawals simultaneously? If no, verify uniqueness enforcement
  • SM-022: Withdrawal timeout: is there a deadline after which a withdrawal can be cancelled/expired?
  • SM-023: Can a withdrawal be stuck forever if admin/manager never advances it? (Griefing vector)
  • SM-024: Partial withdrawal: can investor withdraw some shares and keep others?

5.3 — Fund Lifecycle

  • SM-025: initialize_fund — creates fund with all required fields initialized
  • SM-026: initialize_fund — sets manager, fee, name, vault, shares_mint correctly
  • SM-027: Fund cannot be re-initialized after creation (reinitialization protection)
  • SM-028: Fund closure: is there an instruction to close a fund? If yes, what are the preconditions?
  • SM-029: Fund closure: all investor positions must be settled before fund can close
  • SM-030: Fund closure: all pending withdrawals must be finalized or cancelled
  • SM-031: If no fund closure instruction exists — flag as INFO (funds live forever, rent locked)
  • SM-032: Fund name uniqueness: can two funds by the same manager have the same name? (PDA collision)
  • SM-033: Fund deposit lifecycle: deposit → position created/updated → shares minted
  • SM-034: Fund deposit: position.shares increases by correct amount after deposit

5.4 — Investor Position Lifecycle

  • SM-035: Position creation: when is a position first created? On first deposit?
  • SM-036: Position tracking: does position correctly track total_deposited, total_withdrawn, shares?
  • SM-037: Position closure: when all shares are withdrawn, is the position account closed?
  • SM-038: Position cannot go negative: shares field cannot underflow below 0
  • SM-039: Position total_deposited and total_withdrawn are updated atomically with share changes
  • SM-040: Can a position exist with 0 shares? What happens if further operations are attempted on it?

5.5 — Transition Guard Consistency

  • SM-041: Every state transition checks the CURRENT status before transitioning (pre-condition)
  • SM-042: No transition allows skipping states (e.g., Initiated → Completed without ReadyToFinalize)
  • SM-043: State transitions are atomic — no partial state where transition started but didn't complete
  • SM-044: If a transaction fails mid-execution, no account is left in an inconsistent state
  • SM-045: Replay protection: can the same state transition be triggered twice? (e.g., finalize called twice on same withdrawal)
  • SM-046: After close, the PDA's seeds can be reused for a new account — is this safe? No stale associations?

5.6 — Event Emission

  • SM-047: Every financial state transition emits an event (emit! macro) — deposit, withdrawal, swap, fee
  • SM-048: Events contain all relevant data: amounts, parties, timestamps, account addresses
  • SM-049: Events cannot be spoofed (they're emitted by program execution, not user input)
  • SM-050: Off-chain indexers rely on events — verify events are complete for accurate off-chain state reconstruction

5.7 — Invariant Checks

  • SM-051: fund.total_shares == shares_mint.supply — this invariant holds after every instruction
  • SM-052: fund.total_shares == Σ(all investor_position.shares) — verify no shares are lost or created
  • SM-053: Fund vault balance is consistent with total_assets tracking (if tracked on-chain)
  • SM-054: After every deposit: fund.total_shares increased, fund.total_assets increased
  • SM-055: After every withdrawal: fund.total_shares decreased, fund.total_assets decreased
  • SM-056: After every swap: fund.total_shares unchanged, token balances changed but NAV approximately same

5.8 — Lifecycle Hardening Patterns

Adapted from safe-solana-builder shared-base §26 (state machine & lifecycle integrity). These target subtle lifecycle foot-guns that pass happy-path tests but invert permissions, trap funds, or allow illegal rewrites.

  • SM-057: Sentinel-timestamp safety — no timestamp field uses 0 (or an epoch-era value) as a "special" sentinel while also feeding time arithmetic. expiry_ts = 0 then require!(now < expiry_ts + grace) anchors the window to 1970 and expires instantly. For immediate expiry, store clock.unix_timestamp (now), not 0
  • SM-058: If a timestamp sentinel is genuinely required, it is handled by an explicit branch/flag that bypasses the arithmetic path — the magic value never reaches a comparison like sentinel + grace_period
  • SM-059: Terminal-state cleanup is centralized — every instruction path that reaches the same terminal state (Failed, Closed, Settled) calls ONE shared helper (e.g. on_terminate()) that applies identical side effects (drain, zero accounting, close). No terminal path re-implements cleanup inline
  • SM-060: List each terminal state and enumerate every transition INTO it; confirm all of them invoke the shared cleanup — a single path that skips it (missing lamport drain, un-zeroed reserve) can trap funds or leave phantom liquidity
  • SM-061: Draining assets and zeroing the matching accounting fields happen in the same transaction, with a post-drain backing-invariant check (actual_balance == expected) before finalizing — status flags alone never gate a priced/redeemed/paid action against tracked reserves
  • SM-062: Paired time-gates share ONE canonical deadline_ts — when a single timestamp controls two opposite permissions ("allowed until deadline" vs "cleanup allowed after deadline"), both are derived from the same computed value. Time-gate math is not duplicated inline across handlers
  • SM-063: The two inequalities of a paired gate are exact complements (now <= deadline / now > deadline) — no off-by-one or divergent direction that creates a gap (both false) or overlap (both true) inverting intended permissions
  • SM-064: State transitions are validated against an explicit allowlist matrix — is_allowed_transition(current, next) is checked before any side effect. Exclusion-style guards (status != Initial) are NOT used; they silently permit terminal states
  • SM-065: Terminal states are absorbing — once entered they cannot transition back to a non-terminal state by default. Any intentional recovery path is modeled as a distinct, strictly-precondition'd transition with its own audit event, not an implicit escape
  • SM-066: Access control is not treated as a substitute for transition validation — confirm an authorized actor (admin/manager) still cannot perform an illegal lifecycle rewrite (e.g. Settled → Active) because the transition matrix rejects it independently of who signed
  • SM-067: Sub-state (secondary status / lifecycle locks) is preserved across primary-state transitions, not blindly reset — a primary transition that hardcodes secondary_status = Open can clear a migration-readiness or lockup flag; restore from persisted state or retain conditionally

5.9 — Fixed-Slot Collection & Cached-Aggregate Integrity

These target two subtle, high-loss lifecycle bugs found in real Solana lending/margin programs: iterating fixed-slot arrays that stop at the first empty slot, and stale denormalized aggregates that are not recomputed on same-program mutations. Grep hints:

grep -rn --include="*.rs" -iE "Pubkey::default|== \[0|is_empty|break|for .*positions|for .*obligations|slot|total_collateral|cached|health|cross_margin|recompute|invalidate|dirty" programs/
  • SM-068: Fixed-slot collections skip empties, never stop at the first — when a fixed-size collection (positions / obligations / deposits array) is iterated to compute health, total value, or collateral, does the loop CONTINUE past empty slots (Pubkey::default() / zeroed entries) instead of break/returning at the first empty one, AND are closed middle slots compacted so no filled slot after a gap is skipped? (PASS: iterate all slots, skip-if-empty (continue), or compact-on-close so filled entries are contiguous; FAIL: break on first empty slot causes filled entries beyond a freed gap to be ignored — a user closes a middle position to hide later collateral/debt from the health calc. Jet Protocol had ~$25M at risk from exactly this stop-at-first-empty pattern.)
  • SM-069: Cached aggregates recomputed on EVERY contributing mutation — is any denormalized/cached aggregate (total collateral, account health, cross-margin sums, total value) recomputed or explicitly invalidated on EVERY instruction that mutates a contributing sub-account — including same-PROGRAM state changes (isolate/close/mode-flip/position-move), not only after CPIs? (PASS: every mutator refreshes or dirties the aggregate before it is next read; FAIL: the aggregate is refreshed only on deposit/withdraw or only after a CPI, so an internal state flip — closing a position, switching isolated↔cross, changing margin mode — leaves a stale health/collateral value that under-reports risk. Cypher lost $1.04M this way. This is DISTINCT from the post-CPI .reload() rule (anchor.md): the mutation is in-program, not an external CPI.)

5.10 — Vesting / Cliff Time Math

Vesting, cliff, and lockup schedules are a recurring source of high-severity lifecycle bugs: elapsed-time subtraction that underflows before the start, time units (slot vs unix-timestamp) silently mixed inside one calculation, and cliff/linear boundaries computed off-by-one so the schedule pays out too fast, too early, or double. These pass happy-path tests (which start the clock at a sane value) but break when now < start, at the exact cliff boundary, or under a units mismatch. Grep hints:

grep -rn --include="*.rs" -iE "vest|cliff|lockup|unlock|elapsed|start_(ts|time|slot)|linear|schedule|is_.*started|now *-|current.*-.*start" programs/
  • SM-070: Elapsed-time subtraction cannot underflow — every elapsed = now - start (and any now - last_claim, now - cliff_end) uses checked or saturating subtraction and explicitly guards the now < start case (schedule not yet begun ⇒ elapsed = 0, not a wrapped huge value). (PASS: now.checked_sub(start) / saturating_sub with a pre-start early-return of zero vested; FAIL: raw now - start in unsigned math panics or wraps when now < start — a claim before the start time either bricks or, on a wrapping build, unlocks the entire schedule. Halborn Raydium: cliff-underflow class.)
  • SM-071: Time units are consistent across the whole vesting calc — the schedule's start, cliff, duration, and the value read from Clock are ALL in the same unit (all unix-timestamp seconds OR all slots), never mixed. Confirm the units of every operand feeding the elapsed/vested computation. (PASS: one unit end-to-end, and if slots are used the slot→time assumption is documented and stable; FAIL: start/duration stored as slots but compared against Clock::unix_timestamp — or vice versa — so the vest runs at the wrong rate. Accretion Ellipsis: slot/SlotWindow confusion made vesting complete ~4× too fast.)
  • SM-072: Cliff gate and linear-after-cliff payout are correct and tested — the "has the cliff been reached?" check tests the actual cliff boundary (now >= cliff_end), not merely that vesting was configured/started (start > 0 / is_vesting_started); before the cliff exactly zero is claimable, and after it the linear portion is total * (now - cliff_end) / (duration - cliff) (or the documented formula), never counting pre-cliff time toward the linear release. (PASS: distinct cliff-boundary test plus a linear-release test at, just before, and just after the cliff; FAIL: is_vesting_started only checks a nonzero/started flag and treats that as "cliff passed," releasing cliff tokens early or letting the linear term run from start instead of cliff_end. Halborn Raydium: is_vesting_started checks only > 0; Zenith MetaDAO: cliff/vesting boundary math.)

5.11 — Slot-Denominated Time (SIMD-0525 200 ms Slots / Alpenglow Clock)

A slot is an ordering counter, not a clock. SIMD-0525 halved mainnet slot time to 200 ms (final step epoch 1053, Oct 9, 2026), so every duration a program measures in slots or epochs now elapses in half the wall-clock time; Alpenglow (epoch 1064, Oct 21, 2026) made Clock.unix_timestamp a leader-set value inside a bounded range. The EVM learned this at the Merge (Compound's blocksPerYear), and "block number used as a clock" has been a standard EVM audit item since. See KV-138. Grep hints:

grep -rn --include="*.rs" -iE "clock\.slot|\.slot\b|_slot\b|slots?_(per|until|since|remaining)|epochs?_(per|until)|SLOTS_PER|DEFAULT_TICKS|216_?000|432_?000" programs/
  • SM-073: No duration, deadline, cooldown, timelock, vesting or lockup is measured in slots or epochs under a fixed ms-per-slot assumption; durations use Clock::unix_timestamp. Every slot / epoch-denominated window that remains is converted at the live slot time (200 ms since Oct 2026: a 432,000-slot "2-day" timelock is 24 h, an N-epoch lockup is ~N days) and compared with the security intent it protects. (PASS: seconds end-to-end, or slot / epoch values re-set at activation with the policy re-validated; FAIL: a window that silently halved, giving a hidden-clause proposal, a cliff or a liquidation grace half the reaction time the design assumed. Extends SM-071: "documented and stable" is no longer enough, the slot-to-time ratio changed four times in 2026.)
  • SM-074: Exact-second boundary logic tolerates a leader-set clock: under Alpenglow the leader sets unix_timestamp within [parent_ts, parent_ts + 2 × elapsed slot duration] (the room grows with skipped slots; validators reject values outside it). Any all-or-nothing outcome decided at an exact second (auction close, order expiry, grace end, cliff, option exercise) carries a tolerance at least as large as that bounded drift, or settles through an explicit crank / commit-reveal rather than a leader-timed boundary. (PASS: buffer or crank; FAIL: a leader, or whoever buys the leader's slot, brings the boundary forward by seconds and closes an auction, expires an order or ends a grace period early. Verify activation with getAgGenesisCert (non-null), never by date.)

5.12 — Asymmetry, Write Completeness & Multi-Step Staleness

  • SM-075: List every mirrored pair with file:line for both sides, and diff their account-field writes. Instruction pairs: deposit↔withdraw, stake↔unstake, open↔close, borrow↔repay, lock↔unlock, init↔close, wrap↔unwrap, mint↔burn, request↔execute/cancel. Variant pairs: user vs force_*/emergency_*, single vs batch_*, deposit vs deposit_and_stake, normal vs *_with_referral. A candidate is a field one side writes and the mirror does not, a write in the non-mirror direction, or a field one side reads that the other never refreshes (KV-170).
  • SM-076: Branch pairs inside a handler are diffed (SPL vs Token-2022, native SOL vs SPL, init_if_needed first-time vs existing, Option Some vs None, empty vs non-empty remaining_accounts, exact-in vs exact-out). Look for a check on one branch only, a fee on one branch only, a CPI passing amount on one branch and the post-fee amount on the other, or one branch erroring where the other silently no-ops.
  • SM-077: Field lifecycle: for every persistent field, list all writers and readers. Report fields written but never read (forgotten state), read but never written (always default; e.g. a last_update_slot that makes staleness checks always pass or always fail), and fields with several writers that validate differently (attack the weakest writer).
  • SM-078: Conditional-branch write completeness: in each mutating handler with if/match/early return Ok(()), list the writes per branch. Zero-amount and skip paths must still perform the writes that downstream logic assumes always happen (e.g. last_update = now inside if amount > 0). Symmetric operations (profit/loss, deposit/withdraw) update the same fields across all accounts involved. A size difference of more than 3× between paired branches triggers a line-by-line diff.
  • SM-079: Every update_*/set_* handler that takes a params struct writes every field. Destructure it exhaustively (let S { a, b, c } = p; with no ..): a field added later then breaks the build, and a field that is never written shows up as an unused variable. Option<T> params handle both None and Some (KV-174).
  • SM-080: For every multi-step operation (request→execute, unstake→claim, propose→execute, commit→reveal, order→fill, vesting), classify each parameter as snapshotted at step 1 or re-read at step N. Model an authority change between steps in both directions. The choice must match the promise: user-protective terms are snapshotted, and newly lowered safety limits are re-read. Crank dependency: what happens if the refresh never runs, or a user acts just before or just after it (KV-172)?
  • SM-081: No setter can set a limit below accumulated state (set_max_stake(x) with x < total_staked, set_cap below current supply) without a defined behaviour.
  • SM-082: Multi-call setup (initialize_pool → set_oracle → set_reward_rate) cannot leave user-facing instructions callable while fields are still default (oracle = Pubkey::default(), rate = 0, fee recipient unset). Either an is_configured/status gate exists or setup is atomic. Containers cannot move Draft→Active/Building→Sealed before all parts exist. Rate it as cross-actor griefing when a non-creator can trigger the transition.
  • SM-083: Admin/config setters emit events (extends SM-047 beyond financial transitions). Permissionless handlers do not emit value-looking events without moving value (KV-122). Emitted events carry sequence numbers so indexers can detect gaps.
  • SM-084: In two-step flows, step 2 checks only state that its own step owns. A check copied from step 1 onto state that step 1 legitimately drives to its limit (e.g. remaining > 0 re-checked at redeem after the last reserve) causes a permanent DoS ("bad symmetry").
  • SM-085: A parent account (pool, market, distribution, campaign) cannot be closed while child accounts that reference it (seeds containing parent.key(), has_one = parent) hold balances or live state. An open_children counter is incremented on every child init and decremented on every child close. If the parent is fully deleted and can be re-created at the same seeds, children cannot revive with stale state (use a tombstone, or a generation in the seeds) (KV-175).
  • SM-086: Cleanup incentives line up. A close that only one party may call returns rent to a party with a reason to call it; otherwise anyone may close once a terminal condition holds (claimed == total, expired), with rent going to the stored payer.
  • SM-087: No handler mutates a field in an early branch and then evaluates a later check that was meant to see the pre-mutation value (e.g. a fill-or-kill minimum compared against fields that an earlier no-deposit path zeroed).
  • SM-088: Sentinel semantics are consistent across handlers (0 = never/unlimited, u64::MAX = no cap, empty list = any, Pubkey::default() = none). Every reader rejects, special-cases or uses the sentinel the same way, and expiry windows have matching lower bounds.
  • SM-089: No logic branches on sol_remaining_compute_units(), and no handler processes "as many as fit" and then records completion (cursor, epoch flag, timestamp). Progress is explicit (cursor, MAX_PER_IX), and completion is recorded only when the work is done.
  • SM-090: Every state transition that user funds depend on and that only a keeper/crank/admin signer can perform has a permissionless or time-based fallback after a bounded delay. Otherwise the dependency is documented as a trust assumption.
  • SM-091: No user exit, claim, refund, cancel or settlement path requires closing a token account in the same instruction, because dust, withheld fees and confidential balances make the close fail. Token-account closes are best-effort or a separate crank (KV-168).

Sources: pashov/skills solidity-auditor/references/hacking-agents/asymmetry-agent.md (asymmetry lens, over-strict duplicate check) (MIT, Copyright (c) 2024 AI Skills Contributors) (grep corrected); PlamenTSV/plamen agents/skills/solana/temporal-parameter-staleness/SKILL.md, prompts/solana/generic-security-rules.md (Rule R17), agents/skills/solana/zero-state-return/SKILL.md and prompts/solana/phase4b-scanner-templates.md (MIT, Copyright (c) 2025-2026 Plamen Contributors); sanbir/solana-auditor-skills solana-auditor/references/attack-vectors/attack-vectors-1.md V25 and solana-auditor/references/attack-vectors/attack-vectors-5.md V103 (MIT, Copyright (c) 2024 AI Skills Contributors); qedgen/solana-skills skills/qedgen-auditor/references/category-catalog.md (pda_lifecycle_reuse_after_close, cleanup_incentive_mismatch, execution_order_state_before_check) and skills/qedgen-auditor/references/manual-review-passes.md §3g lifecycle-transition and §3h sentinel-asymmetry sweeps (MIT, Copyright (c) 2025 QEDGen); franpersanchez/solana-audits-skill skill/references/agent-playbooks.md §8 (MIT, Copyright (c) 2026 Fran Pérez); beriktassuly/solana-audit-skill skill/references/taxonomy/dos-compute-budget.md (MIT, Copyright (c) 2026 Berektassuly); solana-foundation/solana-dev-skill skills/solana-dev/references/programs/design-patterns.md (MIT, Copyright (c) 2026); original analysis.

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No third-party reports yet.

Signed by skilld at 586e19e. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 weeks ago.

Activeupdated 4 weeks ago

README badge

README badge for princedotrs/solana-audit