Risks & Security
Status: Active Audience: Grant reviewers, security researchers, internal team Related: build-plan.md · milestones.md
Security Philosophy
Onchain perpetuals custody user funds and manage leverage. Security is not a feature - it is the minimum bar. Our approach is defense-in-depth at the protocol level, with explicit threat modeling, automation testing, and a staged security review roadmap.
Common Attack Surfaces
| # | Attack Surface | Severity | Mitigation |
|---|---|---|---|
| 1 | Oracle manipulation - attacker moves Pyth price to trigger wrongful liquidations or extract profit | Critical | Use Pyth EMA price (not spot); apply deviation circuit breaker (reject >X% moves in one update); require multiple confidence-interval checks |
| 2 | Oracle staleness - stale price causes under-collateralized positions | Critical | Enforce max oracle age (e.g., 30s); reject trades if price feed is stale; pause market if no update within 120s |
| 3 | Missing signer verification - instruction executes without verifying user signed the transaction | Critical | Explicit is_signer checks on all accounts that transfer funds or modify positions; Anchor #[account(signer)] on all user-controlled accounts |
| 4 | CPI target validation - Cross-Program Invocation redirects to malicious program | Critical | Hardcode target program IDs in constants; validate program_id before every CPI; reject dynamic program IDs from user input |
| 5 | Compute budget exhaustion - complex matching runs out of CU mid-transaction | High | Batched matching with per-batch CU budget; early CPI budget audit; pre-compute worst-case CU per order type |
| 6 | Slab data structure bugs - corrupted order book leads to incorrect matching | High | Formal verification of slab insert/remove/scan operations; property-based tests (quickcheck); Bankrun integration tests with adversarial order sequences |
| 7 | Crank / queue stalling - order book matching queue halts if incentives too low or congestion high | High | Inline matching in place_order (no separate crank); priority fee bidding for time-sensitive ops; fallback keeper network for stale queue detection |
| 8 | State bloat & rent exhaustion - dust orders inflate protocol state, hit account size limits | High | Minimum order size enforcement; rent-exempt calculations with buffer; auto-close expired orders; account resizing via reallocation |
| 9 | Flash loan / price manipulation - attacker uses transient capital to move mark price | High | Mark price uses TWAP + EMA (not instantaneous); liquidations require minimum profitability; no flash-loan composability in MVP |
| 10 | Funding rate manipulation - whales manipulate perp price to extract risk-free funding payouts | High | TWAP-based funding rate (not instantaneous mark); clamp funding rate magnitude; max position caps per account; monitor for correlated position clusters |
| 11 | Socialized loss from bad debt - underwater positions exceed insurance fund | High | ADL (auto-deleveraging) as hard backstop; aggressive liquidation parameters (105% maintenance margin); maximum leverage capped at 10x for MVP |
| 12 | Upgrade authority compromise - attacker deploys malicious program upgrade | High | Multi-sig upgrade authority (3-of-5); 48-hour timelock on upgrades; immutable programs where possible (no upgrade flag on core matching) |
| 13 | Frontrunning / MEV - validators or searchers extract value from order flow | Medium | Commit-reveal for large orders (post-MVP); order ID derived from trader key - no private order book state; match events visible on confirmation |
| 14 | Account reinitialization - attacker reinitializes a closed account to steal funds | Medium | Anchor init_if_needed guards; discriminator checks on all account deserialization; close-program enforces rent recovery |
| 15 | Integer overflow / underflow - arithmetic bugs in PnL or margin calculations | Medium | Checked math (SafeMath or Rust overflow checks) in all financial calculations; integration tests that verify boundary positions |
| 16 | Frontend / DNS hijacking - compromised UI redirects user approvals to malicious address | Medium | Subresource integrity (SRI) on all CDN assets; decentralized hosting (IPFS/Arweave); domain monitoring (DNSSec, CAA records); user education on payload verification |
Solana-Specific Implementation Hardening
The following patterns must be enforced across all Anchor programs to mitigate Solana-specific attack vectors:
| Check | Where | Enforcement |
|---|---|---|
| Signer verification | Every instruction modifying user state (margin, positions, vault shares) | #[account(signer)] on user accounts; explicit is_signer runtime checks for any account transferring lamports or tokens |
| Account ownership | All account deserialization | Verify account.owner == program_id before deserializing; use Account::try_from with owner check |
| Account discriminators | All account types | Anchor discriminator (8-byte) on every account; reject accounts with mismatched discriminator |
| CPI target validation | Every Cross-Program Invocation | Target program ID as constant; validate program_id matches expected before invoke_signed |
| Rent-exempt sizing | Account initialization & resizing | Rent::get()?.minimum_balance(size) + 20% buffer; enforce minimum order sizes to prevent dust spam |
| Checked arithmetic | All financial math (PnL, margin, funding, fees) | checked_add, checked_sub, checked_mul, checked_div; fixed-point with explicit precision constants |
| Account close safety | close_account instructions | Require is_signer on authority; verify zero lamports/token balance before close; recover rent to owner |
Security Roadmap
During Development
| Phase | Activity |
|---|---|
| M1 | Threat model documented (this document); attack surface enumerated |
| M2 | Property-based tests for slab matching; Bankrun integration suite with adversarial scenarios |
| M3 | Chaos tests (oracle stall, partial fill floods, rent edge cases); targeted external review of liquidation math ($15k budget) |
| M4 | Friends-and-family test program ($12k budget); internal triage of reported issues; open-source release enables community review |
Mainnet
| Activity | Detail |
|---|---|
| Bug bounty on Immunefi | Bounty pool, focused on critical + high severity |
| Full professional audit | To be completed before mainnet deployment |
| Operational runbook | Incident response, key management, upgrade procedure documented |
| Public post-mortems | Every incident published within 7 days |
Audit Strategy
A full professional audit will be completed before mainnet deployment. Our strategy:
- During grant - targeted external reviews + continuous open-source community review
- Before mainnet - full professional audit (funded separately by the Solana Foundation)
- Post-launch - ongoing bug bounty program
Operational Risks
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Insufficient MM liquidity | Medium | High - CLOB needs two-sided flow | Reference MM bot ships in M4; MM partnerships in Post-M4; liquidity mining incentives |
| RPC / Geyser downtime | Medium | Medium - trading paused | Multi-provider failover (Triton + Helius); local fallback RPC |
| Regulatory uncertainty | Low | High - forced shutdown | Deployed as fully onchain; no KYC in MVP; DAO governance path for fee setters |
| Team attrition | Low | Medium - timeline slip | All code is open-source; collective code ownership (no bus-factor 1) |
| Solana network congestion | Medium | Medium - failed transactions | Priority fee bidding in SDK; transaction retry with increasing fees |
| Frontend / DNS hijacking | Low | Critical - funds drained via UI | SRI on CDN assets; decentralized hosting (IPFS/Arweave); DNSSec/CAA; user payload verification education |
Incident Response Plan
- Detection - onchain monitoring (insurance fund balance, open interest spikes, failed match sequences) + community reports
- Triage - on-call engineer assesses severity within 15 minutes
- Containment - pause market (via multi-sig, bypass 48h timelock for emergency) if funds at risk
- Resolution - patch + deploy via normal upgrade path
- Post-mortem - published within 7 days; root cause, timeline, fixes applied
- Bug bounty payout - if applicable, within 30 days of confirmed report
Insurance Fund
- Capitalization source: 100% of liquidation penalties flow to the insurance fund
- Target size: 5% of open interest (monitored weekly)
- Governance: Protocol-level, no human discretion on payouts
- Solvency: If insurance fund drops below 1% of OI, ADL triggers on all positions and new position opening is blocked until recapitalized