/solana-security-audit:solana-security-auditfrom solana-security-audit
Audits Solana smart contracts across 70+ attack vectors including Anchor, native Rust, and Pinocchio. Covers sealevel attacks, CPI exploits, oracle manipulation, Token-2022 risks, and real-world case studies.
Ships in solana-security-audit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
as truncation)no_allocator! / lazy_program_entrypoint! pitfallsInterfaceAccount)init_if_needed re-initializationAccountLoader footgunsrequire_eq! against a donatable balance)For detailed patterns with full insecure/secure/recommended code, see VULNERABILITY_PATTERNS.md.
evm-contract-audit for Solidity)solana-best-practices)Never run an exploit PoC, fork harness or fixture that a third party sent you outside a sandbox. In October 2026 SEAL warned that fake white-hat researchers were sending Solana teams PoC kits whose poc.mjs ran curl | sh and hid a C2 URL in a field that looked like signature bytes. Read every script before you run it, and run it in a disposable VM or container with no keys, wallets or cloud credentials mounted. See the SEAL advisory.
Signer<'info>, Account<'info, T>, Program<'info, T>). Using raw AccountInfo<'info> bypasses all Anchor protections.#[derive(Accounts)] struct for Anchor to enforce them before the instruction executes.find_program_address) is safe.checked_*() or set overflow-checks = true..reload().InterfaceAccount proves the account is a token account, not that the mint is safe. A permanent delegate can burn your vault, a transfer fee makes received < sent, a transfer hook can reenter you. Screen extensions or allow-list mints.after - before), never the requested amount.MintCloseAuthority, a mint can be closed and its address reused for a different account. Re-validate mint state instead of trusting a cached pubkey.system_program::transfer. A live balance is an upper bound.Account<'info, T> proves the discriminator and owner, not which instance. In a program with many pools or markets, an account from another pool passes every type check. Bind identity with PDA seeds that include the pool id.ctx.accounts.Program data: line. A parser that loses track of the invocation stack after a CPI, or a webhook whose body is trusted without refetching the transaction, accepts events nobody emitted.AdvanceNonceAccount only restores the default blockhash expiry. Check that every privileged handler has the guard, that any opt-out flag's setter is guarded too, and remember it does nothing against a stolen key.Follow these steps:
lib.rs files under programs/ and check for #[program], entrypoint!, or Pinocchio markers.| # | Attack | Severity | What to Check |
|---|---|---|---|
| A0 | Signer Authorization | CRITICAL | Signer<'info> or is_signer check |
| A1 | Account Data Matching | HIGH | constraint or has_one on data fields |
| A2 | Owner Checks | HIGH | Account<'info, T> or manual .owner check |
| A3 | Type Cosplay | HIGH | Account<'info, T> with #[account] discriminator |
| A4 | Initialization | CRITICAL | #[account(init)] or is_initialized flag |
| A5 | Arbitrary CPI | CRITICAL | Program<'info, T> or program ID validation |
| A6 | Duplicate Mutable Accounts | HIGH | constraint = a.key() != b.key() |
| A7 | Bump Seed Canonicalization | CRITICAL | seeds + bump, not user-provided bump |
| A8 | PDA Sharing | HIGH | Unique seeds per user/entity |
| A9 | Closing Accounts | CRITICAL | close = dest or discriminator + force-defund |
| A10 | Sysvar Address Checking | HIGH | Sysvar<'info, T> or address validation |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| B11 | Account Reloading After CPI | HIGH | .reload() after any CPI that modifies accounts |
| B12 | Arithmetic Safety | HIGH | checked_*(), try_floor, multiply-before-divide |
| B13 | SOL Balance Drainage via CPI | CRITICAL | Balance checks before/after CPI |
| B14 | Post-CPI Ownership Verification | HIGH | Re-verify .owner after CPI returns |
| B15 | State Machine Inconsistencies | HIGH | Explicit state enum, validated transitions |
| B16 | Transaction Atomicity Violations | HIGH | Multi-instruction exploit paths |
| B17 | Casting Vulnerabilities | HIGH | try_from() not as for narrowing casts |
| B18 | Authority Transfer Pitfalls | HIGH | Two-step nominate/accept pattern |
| B19 | CPI Signer Forwarding | CRITICAL | Protocol PDAs as CPI authorities, never user wallets |
| B20 | Frontrunning / Slippage | HIGH | minimum_amount_out + deadline parameters |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| C21 | Remaining Accounts | MEDIUM | Manual owner/discriminator/data validation |
| C22 | Seed Collisions | HIGH | Unique prefixes per account type |
| C23 | Ed25519 Introspection | HIGH | Validate position, pubkey, message, nonce |
| C24 | Reallocation Stale Data | MEDIUM | zero_init = true after shrink+grow |
| C25 | Security Dependency Chain | CRITICAL | PDA or hardcoded root anchoring all constraints |
| C26 | Rent-Exemption Violations | MEDIUM | Check lamports stay above rent-exempt threshold |
| C27 | Non-Atomic Init Race | HIGH | Atomic create+init in single tx/CPI |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| D28 | Borsh Deserialization | HIGH | Length pre-check before try_from_slice |
| D29 | invoke vs invoke_signed | CRITICAL | Correct signer seeds, PDA authority |
| D30 | Native Account Closure | CRITICAL | Drain + zero + discriminator + force-defund |
| D31 | Validation Sequence | HIGH | key → owner → signer → writable → disc → data |
| D32 | Unsafe Rust | HIGH | Minimize, validate inputs, // SAFETY: docs |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| E33 | No Auto Discriminators | HIGH | Manual instruction dispatch + type tags |
| E34 | No Built-in Validation | HIGH | All checks manual, same as native |
| E35 | Allocator / Lazy Entry | MEDIUM | no_allocator! panics, lazy parsing skips |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| F36 | Oracle Staleness & Confidence | CRITICAL | get_price_no_older_than, reject wide conf, apply exponent |
| F37 | Manipulable Price Source | CRITICAL | No spot-AMM/illiquid oracle, TWAP + divergence circuit breaker |
| F38 | Oracle Account Substitution | HIGH | Pin feed_id / oracle address, verify owner + VerificationLevel |
| F67 | Collateral Identity Mismatch | CRITICAL | Deposited mint and decimals match the priced asset, checked before any per-type branch |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| G39 | Token Program Confusion | HIGH | Interface/InterfaceAccount, bind to passed token_program |
| G40 | Transfer Fee Accounting | HIGH | Credit measured balance delta, not requested amount |
| G41 | Transfer Hook Risks | HIGH | Checks-effects-interactions, screen/allow-list hook program |
| G42 | Dangerous Mint Extensions | HIGH | Reject PermanentDelegate, freeze, MintCloseAuthority |
| G43 | Amount-Semantics Extensions | MEDIUM | Raw amount for math, screen non-transferable/confidential |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| H44 | init_if_needed Re-init | HIGH | Guard against overwriting initialized state |
| H45 | Zero-Copy / AccountLoader | MEDIUM | load_init on first init, #[repr(C)], #[account(zero)] |
| H46 | Insecure Randomness | HIGH | No clock/slot/blockhash randomness, use VRF |
| H47 | Durable Nonce Replay | HIGH | Program-enforced expiry + sequence on privileged actions |
| H48 | Upgrade Authority Risk | CRITICAL | Multisig + timelock or immutable, verify programdata authority, close deprecated programs, diff builds against the audit |
| H49 | Compute Budget Exhaustion | MEDIUM | Bound loops, cap collections, paginate cranks |
| H50 | State Compression / cNFT | MEDIUM | Verify leaf + proof against on-chain root |
| H51 | Address Lookup Table | LOW | Enforce account identity on-chain, never trust tx construction |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| I52 | Donation / Forced-Balance Griefing | HIGH | Balance invariants use require_gte!, never require_eq! |
| I53 | Share-Price Inflation via Donation | HIGH | Price shares off tracked assets with a virtual offset, reject zero-share deposits |
| I54 | Griefable Liveness | MEDIUM | For each critical check: who can make it fail, and does the failure stick? |
| I55 | Asymmetric Paired Accounting | MEDIUM-HIGH | Compare every write site of a field with every write site of its pair |
| I56 | Rejecting Adverse Observations | HIGH | A loss must be recordable or must freeze exits, never just revert |
| I57 | JIT Deposit Against Stale Rate | MEDIUM-HIGH | Refresh the upstream rate in the same transaction before minting shares |
| I58 | Full-Balance Sweep vs Delta | MEDIUM-HIGH | Credit after - before around your own CPI, never account.amount |
| I59 | Unbounded Subsidy | MEDIUM | Compute subsidized amounts on chain, cap per user, provide a reclaim path |
| I60 | Exposure Base / Grouping | HIGH | Cap = loss-absorbing funds, checked against the same quantity, grouped by explicit failure domain |
| I61 | Denomination Collapse | MEDIUM-HIGH | Fees, yield and claims keep their source asset, solvency checked per asset |
| I68 | Seller-Set Asset Terms | HIGH | Bound rates and terms of bought assets, mark at the lower of cost and model, cap NAV growth |
| I69 | Governance Capture | HIGH | Votes from pre-locked tokens, quorum priced against buy cost, hold-up and outflow cap on treasury moves |
| # | Attack | Severity | What to Check |
|---|---|---|---|
| J62 | Unauthenticated Event Identity | HIGH | emit! reads ctx.accounts.*.key(), never instruction arguments |
| J63 | Unbound Account vs Off-Chain Assumption | MEDIUM | PDA constraints on every path, not only the create branch |
| J64 | Keeper Key on Unvalidated Input | MEDIUM-HIGH | Audit the input channel that steers the keeper key, along with the key |
| J65 | Forged Transaction Provenance | MEDIUM-HIGH | Invocation-stack log parsing, signers from the message, webhooks refetched from RPC |
| J66 | Sponsored Fee Payer | MEDIUM | Capped priority fee set on the server, decode before signing, session bound to the owner |
| J70 | Co-Signer as Policy Boundary | HIGH | Every check the API makes before co-signing also runs in the program |
# Find all Solana programs
rg "#\[program\]" programs/ # Anchor programs
rg "entrypoint!" programs/ # Native programs
rg "pinocchio" Cargo.toml # Pinocchio programs
rg "lazy_program_entrypoint" programs/ # Pinocchio lazy entry
# Check framework version
rg "anchor-lang" Cargo.toml
rg "solana-program" Cargo.toml
rg "pinocchio" Cargo.toml
# Check overflow settings
rg "overflow-checks" Cargo.toml
Anchor gives built-in protections when you use the correct types. Native and Pinocchio programs need manual checks for everything.
# Find all account structs (Anchor)
rg "#\[derive\(Accounts\)\]" programs/ -A 20
# CRITICAL: Find raw AccountInfo usage (bypasses Anchor protections)
rg "AccountInfo<'info>" programs/
# Check for missing Signer type (A0)
rg "authority.*AccountInfo|admin.*AccountInfo|owner.*AccountInfo" programs/
# Check for constraints (A1, A6, A8)
rg "#\[account\(" programs/ -A 3
# Check for unconstrained roots (C25)
rg "Account<'info" programs/ | grep -v "seeds\|has_one\|constraint\|init\|close"
Every AccountInfo<'info> in an Anchor program is a red flag. It should be Signer<'info>, Account<'info, T>, Program<'info, T>, or Sysvar<'info, T> unless documented with /// CHECK:.
# CPI calls (A5, B11, B13, B14, B19)
rg "invoke\(|invoke_signed\(" programs/
rg "\.reload\(\)" programs/
# PDA creation (A7, A8, C22)
rg "create_program_address|find_program_address" programs/
rg "seeds.*bump" programs/
# Account closing (A9, D30)
rg "lamports.*borrow_mut|close\s*=" programs/
rg "CLOSED_ACCOUNT_DISCRIMINATOR" programs/
# Sysvar usage (A10)
rg "load_instruction_at|load_current_index" programs/
# Arithmetic (B12, B17)
rg "\+\s*amount|\-\s*amount|\*\s*amount|/\s*amount" programs/
rg "checked_add|checked_sub|checked_mul|checked_div" programs/
rg "\bas\s+(u8|u16|u32|u64|i8|i16|i32|i64)" programs/
# State management (B15)
rg "enum.*State|status.*=|state.*=" programs/
# Slippage (B20)
rg "swap|trade|exchange" programs/
rg "minimum_amount|slippage|deadline" programs/
# Ed25519 (C23)
rg "ed25519_program|Ed25519" programs/
# Remaining accounts (C21)
rg "remaining_accounts" programs/
# Realloc (C24)
rg "realloc" programs/
# Borsh deserialization without length checks (D28)
rg "try_from_slice|BorshDeserialize" programs/
# invoke vs invoke_signed confusion (D29)
rg "invoke\(|invoke_signed\(" programs/
# Manual account creation (D31)
rg "create_account|CreateAccount" programs/
rg "next_account_info" programs/ -A 10
# Unsafe blocks (D32)
rg "unsafe\s*\{" programs/
# Pinocchio patterns (E33-35)
rg "no_allocator!|lazy_program_entrypoint" programs/
# Oracle security (F36-F38, F67)
rg "get_price_unchecked|load_price_feed_from_account_info" programs/ # unsafe/deprecated reads
rg "get_price_no_older_than|get_feed_id_from_hex|PriceUpdateV2" programs/ # safe Pyth pattern (should exist)
rg "PullFeedAccountData|get_value|switchboard" programs/ # Switchboard
rg "conf|exponent|publish_time|max_stale|maximum_age" programs/ # staleness/confidence handling
rg "reserve|vault.*amount.*/.*amount|sqrt_price|get_spot_price" programs/ # spot-AMM-as-oracle (F37)
rg -n "fn (verify|validate)_\w*(collateral|oracle|asset)\w*" programs/ -A 60 | rg "match|return Ok\(\(\)\)" # F67 early return before the mint check
# Token-2022 / extensions (G39-G43)
rg "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" programs/ # hardcoded classic program
rg "Program<'info, Token>|Account<'info, TokenAccount>|Account<'info, Mint>" programs/ # classic-only types
rg "InterfaceAccount|TokenInterface|Interface<'info" programs/ # multi-standard support
rg "TransferHook|PermanentDelegate|TransferFeeConfig|withheld_amount" programs/
rg "MintCloseAuthority|DefaultAccountState|NonTransferable|ConfidentialTransfer|InterestBearingConfig|CpiGuard" programs/
rg "get_extension|StateWithExtensions" programs/ # extension screening (should exist)
# Modern Anchor & runtime (H44-H51)
rg "init_if_needed" programs/ # H44
rg "zero_copy|AccountLoader|load_init|load_mut" programs/ # H45
rg "Clock::get|unix_timestamp|slot_hashes|recent_blockhash|random|lottery|winner" programs/ # H46
rg "nonce|advance_nonce|DurableNonce" programs/ # H47
rg "programdata|upgrade_authority|BPFLoaderUpgradeab1e|set_upgrade_authority" programs/ # H48
rg "for .* in .*remaining_accounts|while " programs/ # H49 unbounded loops
rg "MerkleTree|concurrent_merkle|account_compression|Bubblegum|verify_leaf" programs/ # H50
rg "AddressLookupTable|lookup_table" programs/ # H51
This code usually looks correct: validated accounts, checked arithmetic, an explicit safety check. The bug is that the check compares against a number an outsider can move.
# I52: exact equality on a balance or bookkeeping figure, the highest-signal grep here
rg -n "require_eq!|assert_eq!" programs/ | rg -i "amount|balance|supply|total|reserve|vault"
# I52: live token balances that feed a check
rg -n "\.amount\b" programs/ -B 4 -A 4 | rg -i "require|assert|check"
# I52: helpers named like invariants, read each one in full since the check can sit far below the signature
rg -n "fn (check|verify|assert|validate)_" programs/ -A 30 | rg "require_eq!|require_gte!|require_gt!"
# I52: lamport invariants
rg -n "lamports\(\)" programs/ | rg -i "require|assert|=="
# I53: share math reading a live balance
rg -n -i "total_assets|share_price|rate" programs/ -A 6 | rg -i "supply|mint_to|checked_div"
# I53: zero-share guard, which should exist
rg -n -i "require_gt!\(shares|zero.?share|virtual_" programs/
Triage every hit by its operator:
>= in the safe direction (live >= tracked): fine, the check absorbs a donation.== between a live balance and tracked state: an I52 finding. Then check whether the gap survives a deposit and withdraw cycle (it almost always does) and whether any instruction can re-sync the tracked value. With no re-sync path, escalate to CRITICAL and say that recovery needs a program upgrade. An admin bookkeeping instruction that can book exactly the surplus (a loss or injection entry) counts as a re-sync path: then rate the finding by how long users stay blocked before an admin acts, usually MEDIUM to HIGH.<=, or == in the other direction: look for the reverse bug, a shortfall that goes unnoticed.Programs often get this right in one helper and wrong in another. When the main asset path uses a tolerant check, grep the helpers for secondary assets and newly added collateral, which is where a strict check tends to survive.
Step 4.6 finds checks that exist and are wrong. This step finds accounting that is never checked. It is mostly reading, and these greps show where to read.
# I55: paired fields, build a write-site table per field and compare the pairs
rg -n "total_\w+\s*[-+]?=|\.checked_(add|sub)\(" programs/ -B 2
rg -n "fn \w*(liquidat|fee|close|migrat|admin|settle)\w*" programs/ -A 40 | rg "checked_sub|checked_add|-=|\+="
# I56: refreshes that reject bad news
rg -n "fn \w*(refresh|update|sync|accrue)\w*" programs/ -A 30 | rg "require!\(.*>=|require_gte!|< 0|return Err"
# I57: upstream valuations read without a refresh in the same transaction
rg -n -i "rate|share_price|index" programs/ -B 4 -A 8
rg -n "fn \w*deposit\w*" programs/ -A 25 | rg -i "refresh|accrue|update|stale"
# I58: whole-balance forwards after a CPI
rg -n "reload\(\)\?;" programs/ -A 12 | rg "\.amount"
# I59: caller-controlled subsidies from a shared treasury
rg -n -i "treasury|subsid|rent" programs/ -B 4 -A 10 | rg "transfer|lamports"
# I60: exposure weight from one base, target or check against another, families from id slices
rg -n -i "max_weight|max_exposure|target" programs/ -B 6 -A 12
rg -n -i "fn parent|family|group" programs/ -A 6 | rg "\[\.\.|\[0\.\."
# I61: value that loses its asset on the way to a claim
rg -n -i "fn \w*claim\w*|accumulated_\w*fee|unclaimed" programs/ -A 20 | rg -i "mint|asset|primary"
# I68: assets the vault takes on, valued on fields the seller set
rg -n -i "fn \w*(sell|buy|purchase|refinance|assign)\w*" programs/ -A 40 | rg -i "rate|apy|interest|nav"
# I69: voting weight from live balances, execution without a hold-up
rg -n -i "quorum|vote_weight|voting_power" programs/ -B 3 -A 6 | rg -i "\.amount|snapshot|locked"
# I54 rate-limiter variant: a live receipt balance valued and APY-gated
rg -n -i "apy|max_rate|rate_limit" programs/ -B 6 -A 6 | rg "\.amount|require|return Err"
I57 has two layers. Check cached upstream rates and also the vault's own cached price. A deposit that only checks the price's age mints shares against yield that is earned but not yet booked, and the next update pays part of it to the new shares.
For I60, write the exposure promise as one inequality (for example "losing any one failure domain is covered by the junior buffer") and check that the code enforces that exact inequality. Then list every position with the programs its CPIs reach, and group them by shared dependency rather than by name.
To find I55 and I56, ask this for each quantity the program tracks: which paths move it, and do they all move its counterpart? No grep can ask it for you. Build the table. A field written in six places whose pair is written in four is the finding, and the two missing paths are usually a fee path and an admin path.
Run this as a pass over the privileged surface. The nonce lives in the transaction, so grepping program code for "nonce" finds nothing.
# 1. The privileged surface
rg -n "Signer<'info>" programs/ -B 6 | rg -i "admin|authority|governance|guardian|operator|owner|keeper|multisig"
rg -n "has_one = (admin|authority)|address = .*(admin|authority)" programs/
# 2. Freshness binding per handler, usually absent, which is the finding
rg -n "valid_until|expires_at|expiry|deadline" programs/
rg -n "seq|sequence|epoch|version" programs/ | rg -i "require|expected"
# 3. Timelocks and two-step authority changes, which mitigate
rg -n -i "propose|timelock|pending_|accept_" programs/
# 4. An existing nonce block through the instructions sysvar
rg -n "sysvar::instructions|load_instruction_at_checked|load_current_index_checked" programs/
If there is no nonce block, recommend one (see the H47 mitigation in VULNERABILITY_PATTERNS.md).
If there is one, look for gaps. List the privileged handlers yourself and compare that list with the handlers carrying the guard. Never trust the list of files a PR touched. Two things hide gaps, so check them by hand:
Context<T> may carry no gate itself, with the privileged signer inside an embedded shared accounts struct. Resolve one level of nesting before comparing.Then confirm: the sysvar account is pinned with address = sysvar::instructions::ID, any opt-out flag's setter is guarded too, the guard runs before any state change, and a zero default in reused padding means blocked. Say in the report that this only restores the blockhash expiry. It does not bind freshness and does not help against a stolen key.
For each privileged instruction, answer the checklist in H47 of VULNERABILITY_PATTERNS.md.
Report it as: "transfer_admin, change_config and claim_fees carry no program-enforced expiry or sequence number. A signature obtained today (durable nonce, social engineering, or an old hardware-wallet approval) stays executable indefinitely. Recommend an expiry and a sequence number, or a timelocked two-step flow with a guardian veto." Flag single-step authority transfers here too, since they make this worse (B18).
Run this only when the repo ships the consumers (indexer, webhook receiver, keeper, worker, bot, transaction-building API) with the program. If it does, they are in scope: an attacker who cannot move funds on chain can often make a trusted keeper move them.
# 1. What can the keeper key do, and does any of it act for a user?
rg -n -i "keeper|crank|operator|bot" programs/ -B 4 -A 4 | rg "Signer|address =|has_one|constraint"
# 2. Events built from arguments instead of accounts
rg -n "emit!\(" programs/ -A 10 | rg -v "ctx\.accounts|\.key\(\)"
# 3. Off-chain consumers of those events
rg -l -i "keeper|crank|cron|worker|queue|indexer" --glob '!programs/**' .
# 4. J65: how does the consumer decide a log is ours, and who signed?
rg -n "Program data:|logMessages|invoke \[" --glob '!programs/**' . -B 3 -A 12
rg -n -i "webhook|app\.post|router\.post" --glob '!programs/**' . -A 20 | rg -i "auth|secret|signature|getTransaction"
# 5. J66: what does a sponsored fee payer sign?
rg -n -i "feePayer\s*=|partialSign|sponsor|priorityFee|setComputeUnitPrice" --glob '!programs/**' . -B 4 -A 6
# 6. J70: which checks exist only in the co-signing API?
rg -n -i "cosigner|co_signer|api_signer|backend_signer" programs/ -B 3 -A 6
Then trace one path end to end: instruction, emitted event, indexer row, keeper action, on-chain effect. At each hop, ask what an unprivileged attacker controls. For the first hop, ask how the consumer learned of the transaction (a webhook body, or a refetch from its own RPC) and how it decided which program wrote each log line. A wrapper program can CPI into yours and then log a fake event of its own. Look hard at consumer checks where both sides of a comparison come from the same event field: they read as validation and enforce nothing. Also check the queue for retry caps, a terminal failure state, and whether one job type can starve another.
For each finding, verify:
#[derive(Accounts)] struct?.reload() after every CPI that modifies accounts read later?checked_*() or is overflow-checks = true in Cargo.toml?>= in the safe direction, and can a third party push it out of range with a donation? If the failure sticks, is there an on-chain re-sync path?Use the finding template below. Group by severity.
## [SEVERITY] #ID: Attack Name
**Location**: `programs/my-program/src/lib.rs:45-60`
**Description**: Brief explanation of the vulnerability.
**Vulnerable Code**:
(code block showing the issue)
**Attack Scenario**:
1. Step-by-step exploit description
**Recommended Fix**:
(code block showing idiomatic fix for the detected framework)
**Reference**: solana-security-audit #ID
asrequire_eq!For each vulnerability class, write negative tests that attempt the exploit:
import * as anchor from "@coral-xyz/anchor";
describe("security audit tests", () => {
// A0: Pass non-signer as authority
it("rejects unsigned authority", async () => {});
// A1: Pass mismatched token account
it("rejects token not owned by signer", async () => {});
// A3: Pass wrong account type
it("rejects metadata account as user account", async () => {});
// A5: Pass fake token program
it("rejects non-SPL token program", async () => {});
// A6: Pass same account for both user_a and user_b
it("rejects duplicate mutable accounts", async () => {});
// A9: Revive closed account
it("prevents closed account revival", async () => {});
// B11: Read stale data after CPI
it("returns correct values after CPI", async () => {});
// B12: Overflow arithmetic
it("rejects overflowing deposit", async () => {});
// B13: SOL drainage via CPI
it("prevents unauthorized lamport transfer via CPI", async () => {});
// B15: State machine skip
it("rejects out-of-order state transition", async () => {});
// B17: Casting overflow
it("rejects u64 value that truncates to u32", async () => {});
// B20: Missing slippage
it("rejects swap below minimum output", async () => {});
// C25: Unconstrained root
it("rejects fake config account in dependency chain", async () => {});
// F36: Stale / low-confidence oracle
it("rejects a price update older than max age", async () => {});
it("rejects a price with an excessively wide confidence interval", async () => {});
// F38: Oracle substitution
it("rejects a price account for the wrong feed", async () => {});
// F67: Collateral identity
it("rejects every supported mint deposited under another collateral config", async () => {});
it("rejects collateral whose mint decimals differ from the config", async () => {});
// G40: Fee-on-transfer over-credit
it("credits only the received amount for a transfer-fee mint", async () => {});
// G42: Dangerous mint extension
it("rejects a collateral mint with a permanent delegate", async () => {});
// H44: init_if_needed re-init
it("prevents re-initializing an existing account", async () => {});
// H46: Insecure randomness
it("does not derive winner selection from clock/slot", async () => {});
// H47: Durable nonce / stale admin authorization
it("rejects an admin action after its signed expiry", async () => {});
it("rejects a second pre-signed admin action once the sequence moved", async () => {});
// one table-driven case per privileged instruction, so new admin instructions are covered too
it("rejects every admin instruction inside a durable-nonce transaction", async () => {});
it("rejects turning off the nonce guard from inside a nonce transaction", async () => {});
// I52: Donation griefing, the most valuable test in this section
it("still deposits after an unsolicited transfer into the vault token account", async () => {});
it("still withdraws after an unsolicited transfer into the vault token account", async () => {});
it("still refreshes after a 1-unit donation to every program-owned token account", async () => {});
it("still works after a lamport top-up to a program-owned PDA", async () => {});
// I53: Share-price inflation
it("rejects a deposit that would mint zero shares", async () => {});
it("prices shares correctly after a large donation to the vault", async () => {});
// I55: Paired accounting
it("keeps pool totals equal to the sum of user values after liquidation and fee paths", async () => {});
it("keeps cap capacity used until tokens leave custody", async () => {});
// I56: Adverse observation
it("records a loss on refresh, or freezes exits, instead of reverting", async () => {});
it("blocks exits priced against a value older than the latest refresh", async () => {});
// I57: JIT deposit
it("gives a new depositor no share of yield earned before the deposit", async () => {});
// I58: Sweep vs delta
it("withdraws correctly when the landing token account was pre-funded", async () => {});
it("does not book a pre-existing landing balance as proceeds or yield", async () => {});
// I59: Subsidy
it("refuses to subsidize a second account for the same user", async () => {});
// I54 rate-limiter variant
it("still refreshes after receipt tokens are donated to the receipt account", async () => {});
// I57 own-price variant
it("gives a deposit made just before an update no share of that update's gain", async () => {});
// I60: Exposure base and grouping
it("rejects a position larger than the junior buffer after large withdrawal requests", async () => {});
it("caps the sum of positions that share one bridge or adapter", async () => {});
// I61: Denomination
it("settles a fee charged in a secondary asset in that asset", async () => {});
// I68: Seller-set terms
it("rejects buying a loan whose rate exceeds the vault limit", async () => {});
it("redeems at the pre-purchase price in the same transaction as a purchase", async () => {});
// I69: Governance
it("gives no voting weight to tokens deposited after the proposal was created", async () => {});
it("refuses to execute a treasury transfer before the hold-up period ends", async () => {});
// J62: Event identity
it("emits the signer's key, not a key passed in instruction data", async () => {});
it("ignores an event that references another user's job id", async () => {});
// J65 / J66 (consumer-side tests)
it("ignores a Program data log written by a wrapper after a depth-2 CPI returns", async () => {});
it("rejects a webhook body for a signature RPC cannot find", async () => {});
it("refuses to sponsor a transaction whose priority fee exceeds the cap", async () => {});
// J70: replay each co-signed instruction with out-of-policy inputs and the co-signer's signature
it("rejects an out-of-policy action even when co-signed", async () => {});
});
Write the donation test first. For every program-owned token account, send 1 unit from an unrelated wallet, then run the full instruction set. Anything that breaks is an I52 finding. The test is a few lines long and also covers code added later.
// I52 harness sketch
const stranger = Keypair.generate();
await mintTo(conn, payer, mint, strangerAta, authority, 1);
await transfer(conn, stranger, strangerAta, vaultAta, stranger, 1); // no consent needed
await program.methods.deposit(amount).accounts({ /* ... */ }).rpc(); // must still succeed
await program.methods.withdraw(amount).accounts({ /* ... */ }).rpc();
await program.methods.settleYield().accounts({ /* ... */ }).rpc();
| Exploit | Impact | Root Cause | Pattern |
|---|---|---|---|
| Wormhole Bridge | $320M+ | Missing sysvar validation | A10 |
| Cashio | $48-52M | Missing account/mint validation (account confusion) | A1, A2 |
| Crema Finance | ~$8.8M | Missing owner check on passed "tick" account | A2, C21 |
| Mango Markets | $115M | Oracle price manipulation (thin market, in-tx) | F36, F37 |
| Loopscale (2025) | $5.8M | Illiquid collateral priced off manipulable spot source | F37 |
| Loopscale (Nov 2026) | ~$933K, restored | kySOL priced as zBTC through a validator early return, then vault NAV inflated by a seller-set loan rate, every step co-signed by its API | F67, I68, J70 |
| Nirvana (2022) | $3.5M | Bonding-curve price manipulation via flash loan | F37 |
| DeFiTuna (Jul 2026) | ~$580K | Fixed-point truncation in solvency check + "empty = healthy" default | B12, B17 |
| Jet Protocol | -- | PDA without caller validation | A8 |
| Saber Stable Swap | ~$1M/day potential | Rounding direction (round vs floor) | B12 |
| Solend Rent Thief | ~0.008 SOL/iter | Non-atomic account init race condition | C27 |
| Drift (Apr 2026) | ~$285M | Durable-nonce pre-signing of council multisig + social-engineered fake oracle | H47 (+ operational) |
| Aquifer (Aug 2026) | ~$2.47M | Swap took a caller-supplied token program and unowned fake token accounts, paid out first, never checked the vault balance rose | A2, A5, I58 |
| Across Solana relayer (Jul 2026) | <$4M | Relayer accepted forged deposit events with no discriminator or self-CPI origin check | J65 |
| BonkDAO (Jul 2026) | ~$20M | Bought tokens passed a treasury transfer at 2.9% turnout | I69 |
| Raydium legacy AMM V3 (Jun 2026) | $1.34M | Deprecated program never checked the LP mint on withdraw | A1, H48 |
| Solana web3.js (2024) | ~$160-190K | Supply-chain: backdoored npm package stole keys | Operational |
| Step Finance (Jan 2026) | ~$27-30M | Admin key compromise (social engineering) | Operational |
| ERC-4626 inflation attack (bug class, all chains) | varies | Share price read off a donatable balance, deposit rounds to zero | I53 |
| Donation DoS (bug class, common audit finding) | liveness | require_eq! between a program-owned token balance and internal bookkeeping | I52 |
The table labels the Drift, web3.js, and Step incidents operational because a review of on-chain program code cannot catch them. Auditors should still flag the underlying risk (durable-nonce assumptions, dependency supply chain, single-key admin authority). BonkDAO had no code bug either: its governance parameters were the bug. Loopscale's code-level cause comes from one researcher's analysis, so treat it as unconfirmed until Loopscale publishes a post-mortem. Other 2026 losses came from leaked operator keys (validator operators, the Bloom and King trading bots) and are out of scope for a program review.
cargo-audit: Dependency vulnerability scannercargo clippy: Lint for common Rust mistakespyth-solana-receiver-sdk, PriceUpdateV2, get_price_no_older_thanPullFeedAccountData, staleness/variance gatingInterfaceAccount, TokenInterface for Token-2022What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
solana-security, smart-contract-audit, anchor, rust, sealevel, cpi-security
Other plugins' skills for the same job
npx claudepluginhub gabrielkoerich/skills --plugin solana-security-audit