# behavioral-state-analysis

Token-efficient smart contract security auditing via Behavioral State Analysis (BSA). Scopes analysis to contract type, runs only relevant threat engines, and uses tiered output depth. Use for auditing smart contracts, security reviews, or DeFi threat modeling.

- **Kind:** skill
- **Source:** https://github.com/quillai-network/qs_skills
- **Page:** https://forefy.com/skills/873e192f-8298-4db5-87f6-3e2ccdba9c49
- **API (JSON + files):** https://forefy.com/api/asr/873e192f-8298-4db5-87f6-3e2ccdba9c49

---

## SKILL.md

---
name: behavioral-state-analysis
description: Token-efficient smart contract security auditing via Behavioral State Analysis (BSA). Scopes analysis to contract type, runs only relevant threat engines, and uses tiered output depth. Use for auditing smart contracts, security reviews, or DeFi threat modeling.
---

# Behavioral State Analysis (BSA)

Audit smart contracts by extracting behavioral intent, then systematically breaking it across security dimensions.

## When to Use

- Smart contract security audits
- DeFi protocol threat modeling (DEXs, lending, staking, vaults)
- Cross-contract attack surface analysis
- Vulnerability prioritization with confidence scoring

## When NOT to Use

- Pure context building (use audit-context-building)
- Entry point identification only (use entry-point-analyzer)
- Single-dimension only (use semantic-guard-analysis or state-invariant-detection)

## Token Budget Rules

**Follow these strictly to avoid context exhaustion:**

1. **Be terse.** Use bullet points and tables, not prose. No filler sentences.
2. **Smart scope first.** Classify the contract type in Phase 1, then run ONLY relevant engines in Phase 2 (see engine selection matrix below).
3. **Tiered output depth:**
   - Critical/High findings → full detail + PoC code
   - Medium findings → root cause + exploit scenario (no PoC)
   - Low/Info findings → one-line description only
4. **No redundant analysis.** If a dimension has no attack surface (e.g., no value flows = skip ETE), say "N/A" and move on.
5. **Cap Phase 1 output** to ≤30 lines per contract. List invariants and states, skip verbose specification documents.
6. **PoC generation** only for Critical and High severity findings. For others, describe the exploit path in ≤3 steps.
7. **Combine phases in output** — don't repeat findings across phases. Each finding appears once with all metadata inline.

## Pipeline

### Phase 1: Behavioral Decomposition (keep brief)

Extract intent from code and docs. Output per contract:

```
Contract: <Name>
Type: <DeFi/Token/Governance/NFT/Utility/Proxy>
States: [list]
Key Invariants (≤5):
  - <invariant>
Privileged Roles: [list]
Value Entry/Exit Points: [list or "none"]
```

**Then select engines:**

| Contract Type | Run ETE | Run ACTE | Run SITE |
|--------------|---------|----------|----------|
| DeFi (DEX/lending/vault/staking) | Yes | Yes | Yes |
| Token (ERC20/721/1155) | Yes | Lite | Lite |
| Governance/DAO | Lite | Yes | Yes |
| NFT marketplace | Yes | Yes | Lite |
| Utility/Library | No | Lite | Lite |
| Proxy/Upgradeable | No | Yes | Yes |

**Lite** = check only the top-priority item for that engine (see below).

### Phase 2: Threat Modeling (selected engines only)

Run only the engines selected above. For each engine, analyze in this priority order — stop if contract surface is exhausted:

**Economic Threat Engine (ETE):**
1. Value flow tracing — where can value enter/leave? Any sinks or circular flows?
2. Economic invariant verification — does `deposits == withdrawals + balance` hold?
3. Incentive analysis — any rational actor exploits (MEV, sandwich, griefing)?

**Access Control Threat Engine (ACTE):**
1. Unprotected privileged functions — any admin/owner actions callable by anyone?
2. Role escalation paths — can `User → [actions] → Admin`?
3. msg.sender vs tx.origin confusion; signature replay

**State Integrity Threat Engine (SITE):**
1. Non-atomic state updates — partial updates before external calls?
2. Sequence vulnerabilities — initialization bypass, unexpected call ordering?
3. Cross-contract stale data or reentrancy vectors

**Lite mode** = run only item #1 from that engine's list.

### Phase 3: Exploit Verification

For each hypothesis from Phase 2:
- Build attack sequence (≤5 steps)
- For Critical/High: generate minimal Foundry/Hardhat PoC (keep code short — test the specific vuln, not a full test suite)
- Quantify impact: Critical (all funds/system) | High (significant loss/privesc) | Medium (griefing/DOS) | Low (info/best practice)

### Phase 4: Score & Prioritize

Score: `Confidence = (Evidence × Feasibility × Impact) / FP_Rate`

| Factor | 1.0 | 0.7 | 0.4 | 0.1 |
|--------|-----|-----|-----|-----|
| Evidence | Concrete path, no deps | Specific state needed | Pattern-based | Heuristic |
| Feasibility | PoC confirmed | Achievable state | External conditions | Infeasible |

Impact: 5=total loss, 4=partial loss, 3=griefing, 2=info leak, 1=best practice
FP_Rate: 0.05 (known pattern) → 0.15 (moderate) → 0.40 (weak) → 0.60 (heuristic)

**Prioritization:** Report findings ≥10% confidence. Never suppress Impact ≥4.

## Finding Format (use for every finding)

```
### [F-N] Title
Severity: Critical|High|Medium|Low  |  Confidence: X%
Location: contract.sol#L10-L25, functionName()
Root Cause: <1-2 sentences>
Exploit: <numbered steps, ≤5>
Impact: <1 sentence with quantified risk>
Fix: <code diff or 1-2 sentence recommendation>
PoC: <only for Critical/High — minimal test code>
```

## Advanced Checks (run only if relevant to contract type)

- **Cross-contract:** Map external call chains `A→B→C`, test transitive trust
- **Time-based:** `block.timestamp` manipulation, expired signatures, replay
- **Upgradeable:** Storage collisions, re-initialization, migration atomicity

## Mindset

- "Standard function" → can behave non-standardly in context
- "Admin is trusted" → model admin compromise, check excessive powers
- "Known pattern" → novel interactions in specific contexts
- "Small value" → compounds; griefing scales
- "Trusted external contract" → trust boundaries shift; verify actual code

## references

```

```

## references/confidence-scoring.md

# Confidence Scoring Deep-Dive Reference

> **Optional reference.** Only read this file when you need detailed scoring examples or FP rate estimation guidance beyond what SKILL.md provides.

## Formula

`Confidence = (Evidence_Strength × Exploit_Feasibility × Impact_Severity) / False_Positive_Rate`

## Evidence Strength (0-1)

| Score | Criteria |
|-------|----------|
| 1.0 | Concrete code path, no external dependencies |
| 0.7 | Path depends on specific but achievable state |
| 0.4 | Pattern-based theoretical vulnerability |
| 0.1 | Heuristic suggestion without concrete evidence |

## Exploit Feasibility (0-1)

| Score | Criteria |
|-------|----------|
| 1.0 | PoC confirmed and executes successfully |
| 0.7 | Requires specific achievable contract state |
| 0.4 | Requires external conditions (oracle manipulation, MEV infra) |
| 0.1 | Theoretically possible, practically infeasible |

## Impact Severity (1-5)

5=Complete fund loss/system compromise, 4=Partial loss/privesc, 3=Griefing/DOS, 2=Info leak, 1=Best practice

## False Positive Rate Estimation

- 0.05: Well-known patterns (reentrancy without guard)
- 0.15: Moderate patterns (access control gaps)
- 0.40: Weak patterns (potential front-running)
- 0.60: Heuristic suggestions

## Quick Examples

- Reentrancy in withdraw (E=1.0, F=1.0, I=5, FP=0.05) → 100 → cap at 99%
- Front-running auction (E=0.7, F=0.6, I=3, FP=0.3) → 4.2 → 42%
- Gas optimization (E=0.4, F=0.1, I=1, FP=0.5) → 0.08 → 8%

## Prioritization

- Report all ≥10% confidence
- Highlight ≥70% as Critical
- 30-70% flagged for review
- <30% in appendix
- Never suppress Impact ≥4 regardless of confidence

## references/threat-engines.md

# Threat Engine Deep-Dive Reference

> **Optional reference.** Only read this file when performing a deep audit that needs granular engine checklists beyond what SKILL.md provides. Do NOT load this for standard audits.

## Economic Threat Engine (ETE) — Detailed Checklists

### Value Flow Tracing
- Map all entry/exit points: deposit, stake, withdraw, claim, liquidate, emergencyDrain
- Identify: value sinks (trapped funds), unexpected sources (minting), circular flows (flash loan amplification)

### Economic Invariant Verification
- Core: `sum(deposits) == sum(withdrawals) + contractBalance`
- Test under: normal ops, extreme values (uint256 edge), concurrent txs, oracle manipulation, flash loans

### Incentive Analysis
- For each public function: `if Benefit > Cost → exploit vector`
- Check: MEV opportunities, sandwich vectors, front-running, griefing (harm others at low cost)

## Access Control Threat Engine (ACTE) — Detailed Checklists

### Role Hierarchy
- Map complete role graph: Owner → Admin → Pauser/FeeManager; Governance → Executor; Guardian
- Per function: which roles can call, is check correct, is role assignment/revocation controlled

### Permission Boundary Testing
- Build matrix: Function × Role → Expected vs Actual access
- Flag any discrepancy between expected and actual permissions

### Privilege Escalation
- Test: user self-granting admin, admin bypassing timelock, msg.sender/tx.origin confusion
- Test: signature replay for unauthorized access, re-initialization to reset roles

## State Integrity Threat Engine (SITE) — Detailed Checklists

### State Transition Validation
- Per state-modifying function: are ALL variables updated atomically?
- Check for partial updates (e.g., balance decremented but pendingWithdrawals not updated)

### Sequence Vulnerabilities
- Test unexpected orderings: deposit before init, withdraw before deposit, action after pause
- Test re-initialization attacks: `initialize()` callable more than once

### Cross-Contract State Sync
- When A depends on B: test stale data, B paused, B returns 0, B reverts, B upgraded maliciously
- Verify all edge cases handled in caller's logic

