Defi Risk Analysis
Analyze a DeFi protocol's risk profile across smart contract, off-chain, and track-record dimensions. Use when the user wants a risk analysis of a DeFi project, to check protocol security, or to as...
Analyze a DeFi protocol's risk profile across smart contract, off-chain, and track-record dimensions. Use when the user wants a risk analysis of a DeFi project, to check protocol security, or to assess risk. Trigger words include "risk analysis", "analyze protocol", "audit defi", "check security", "defi risk", "protocol vulnerability", "is it safe".
Install
Quick install
npx skills add https://github.com/truenorth-lj/crypto-project-security-skillnpx skills add truenorth-lj/crypto-project-security-skill --agent claude-codenpx skills add truenorth-lj/crypto-project-security-skill --agent cursornpx skills add truenorth-lj/crypto-project-security-skill --agent codexnpx skills add truenorth-lj/crypto-project-security-skill --agent opencodenpx skills add truenorth-lj/crypto-project-security-skill --agent github-copilotnpx skills add truenorth-lj/crypto-project-security-skill --agent windsurfMore install options
Shorthand — useful for multi-skill repos:
npx skills add truenorth-lj/crypto-project-security-skillManual — clone the repo and drop the folder into your agent's skills directory:
git clone https://github.com/truenorth-lj/crypto-project-security-skill.gitcp -r crypto-project-security-skill ~/.claude/skills/defi-risk-analysis
Analyze a DeFi protocol's risk profile across smart contract, off-chain, and track-record dimensions. Use when the user wants a risk analysis of a DeFi project, to check protocol security, or to assess risk. Trigger words include "risk analysis", "analyze protocol", "audit defi", "check security", "defi risk", "protocol vulnerability", "is it safe".
---
name: defi-risk-analysis
description: Analyze a DeFi protocol's risk profile across smart contract, off-chain, and track-record dimensions. Use when the user wants a risk analysis of a DeFi project, to check protocol security, or to assess risk. Trigger words include "risk analysis", "analyze protocol", "audit defi", "check security", "defi risk", "protocol vulnerability", "is it safe".
version: 2.1.0
allowed-tools: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch
metadata:
openclaw:
requires:
bins:
- curl
- jq
optional_bins:
- solana
---
DeFi Risk Analysis Skill
Perform a comprehensive risk analysis of a DeFi protocol. This skill systematically evaluates smart contract risk, off-chain risk (governance, team, operations), and track record (historical incidents, battle-testing, response capability).
This is a structured risk analysis, NOT a formal smart contract audit — it reviews publicly available information and on-chain state to surface risk signals. Formal audits require line-by-line code review by professional auditing firms.
Input
The user provides one or more of:
- Protocol name (e.g., "Aave", "Drift", "GMX")
- Protocol website or DeFiLlama URL
- Contract addresses or chain
Workflow
Step 0: Quick Triage (Red Flag Scan)
Before deep analysis, run a quick triage to decide analysis priority:
- DeFiLlama data check:
# Fetch all protocols and fuzzy-match by name
curl -s 'https://api.llama.fi/protocols' | jq -r '.[] | select(.name | test("{protocol}"; "i")) | "\(.slug) -- \(.name) -- TVL: \(.tvl)"'
If no match, try partial name or check the protocol's website for its DeFiLlama listing.
Then fetch full data with the resolved slug: curl -s 'https://api.llama.fi/protocol/{slug}' to get:
- Current TVL and TVL history (sharp drops = red flag)
- Number of audits listed
- Chain(s)
- GoPlus token security check: If the protocol has a governance/utility token on an EVM chain, run
./scripts/goplus-check.sh token <chain_id> <contract_address>or call the API directly:
curl -s "https://api.gopluslabs.io/api/v1/token_security/<chain_id>?contract_addresses=<address>"
Extract these red flags from the response:
is_honeypot = 1-- token is a honeypot (CRITICAL)honeypot_with_same_creator = 1-- creator has deployed honeypots (CRITICAL)is_open_source = 0-- contract not verified (HIGH)hidden_owner = 1-- hidden ownership mechanism (HIGH)owner_change_balance = 1-- owner can modify balances (HIGH)selfdestruct = 1-- contract can self-destruct (HIGH)can_take_back_ownership = 1-- can reclaim ownership after renouncing (HIGH)is_proxy = 1-- upgradeable proxy (MEDIUM, cross-reference with Step 2)is_mintable = 1-- unlimited minting possible (MEDIUM)slippage_modifiable = 1-- owner can change tax/slippage (MEDIUM)transfer_pausable = 1-- transfers can be paused (MEDIUM)is_blacklisted = 1-- has blacklist functionality (MEDIUM)
Also note: buy_tax, sell_tax, holder_count, lp_holders (lock status), and trust_list status.
Chain IDs: 1=Ethereum, 56=BSC, 137=Polygon, 42161=Arbitrum, 10=Optimism, 43114=Avalanche, 8453=Base, 324=zkSync. Solana is NOT supported by GoPlus token security API.
Solana token fallback: GoPlus does not support Solana SPL tokens. For Solana protocols, use these alternatives instead:
- RugCheck:
curl -s 'https://api.rugcheck.xyz/v1/tokens/{mint_address}/report'-- returns risk score, mutable metadata, freeze authority, mint authority, top holders, LP lock status - Birdeye:
curl -s -H 'X-API-KEY: public' 'https://public-api.birdeye.so/public/token_security?address={mint_address}'-- holder concentration, LP info - Manual checks: On Solana Explorer, verify: (1) mint authority (revoked = safer), (2) freeze authority (revoked = safer), (3) metadata mutability, (4) top holder concentration
Record the source as "RugCheck" or "Birdeye" instead of "GoPlus" in the report. If none of the alternatives return data, record "Solana Token Check: UNAVAILABLE" and note the gap.
Error handling: GoPlus is a free API with undocumented rate limits. If the API returns an error, empty result, or times out:
- Record "GoPlus: UNAVAILABLE" in the report rather than omitting the section
- Wait 5 seconds and retry once
- If still failing, proceed with the analysis without GoPlus data and note the gap in Information Gaps
- GoPlus address check (optional): If specific admin/deployer addresses are known, check for malicious history:
curl -s "https://api.gopluslabs.io/api/v1/address_security/<address>?chain_id=<chain_id>"
Flags: cybercrime, money_laundering, phishing_activities, stealing_attack, sanctioned, honeypot_related_address, malicious_mining_activities, number_of_malicious_contracts_created.
- Immediate red flags (any = escalate to CRITICAL triage):
- TVL = $0 or dropped >50% in 30 days
- No audits listed on DeFiLlama
- Protocol age < 6 months with TVL > $50M
- Anonymous team with no prior track record
- Closed-source contracts
- GoPlus: honeypot detected or creator has honeypot history
- GoPlus: hidden owner or owner can change balances
- GoPlus: admin/deployer address flagged as malicious
- Quick Triage Score (compute for the report, 0-100):
Start at 100. Subtract EXACTLY the listed points for each flag that applies.
Do NOT adjust, round, or add mitigating bonuses -- the score is mechanical.
CRITICAL flags (-25 each):
[ ] GoPlus: is_honeypot = 1
[ ] GoPlus: honeypot_with_same_creator = 1
[ ] GoPlus: hidden_owner = 1
[ ] GoPlus: owner_change_balance = 1
[ ] TVL = $0
[ ] Admin/deployer address flagged as malicious
HIGH flags (-15 each):
[ ] Closed-source contracts (is_open_source = 0)
[ ] Zero audits listed on DeFiLlama
[ ] Anonymous team with no prior track record
[ ] GoPlus: selfdestruct = 1
[ ] GoPlus: can_take_back_ownership = 1
[ ] No multisig (single EOA admin key)
[ ] Single bridge provider for cross-chain deployments on 5+ chains (Kelp lesson)
[ ] Lending/CDP protocol accepts LRT, bridge token, or synthetic asset as collateral without a *binding* per-asset cap (supplyCap < 20% of total collateral TVL; see Step 4.5.5). This flag fires regardless of current % exposure -- ungated collateral can grow. Insurance-vs-largest-exposure is rated separately in Step 4.5 and must not also be flagged here.
MEDIUM flags (-8 each):
[ ] GoPlus: is_proxy = 1 AND no timelock on upgrades
[ ] GoPlus: is_mintable = 1
[ ] Protocol age < 6 months with TVL > $50M
[ ] TVL dropped > 30% in 90 days
[ ] Multisig threshold < 3 signers (e.g., 2/N)
[ ] GoPlus: slippage_modifiable = 1
[ ] GoPlus: transfer_pausable = 1
[ ] No third-party security certification (SOC 2 / ISO 27001 / equivalent) for off-chain operations
[ ] **This protocol's** bridge/wrapped/LRT token is accepted as collateral on 3+ external lending protocols without rate limits (issuer-side downstream-cascade risk; for the inverse — this protocol *accepting* such collateral — see Step 4.5 / the HIGH flag above)
LOW flags (-5 each):
[ ] No documented timelock on admin actions
[ ] No bug bounty program
[ ] Single oracle provider
[ ] GoPlus: is_blacklisted = 1
[ ] Insurance fund / TVL < 1% or undisclosed
[ ] Undisclosed multisig signer identities
[ ] DAO governance paused or dissolved
[ ] No published key management policy (HSM, MPC, key ceremony)
[ ] No disclosed penetration testing (infrastructure, not just smart contract audit)
[ ] Custodial dependency without disclosed custodian certification
Floor at 0. Score meaning:
80-100 = LOW risk | 50-79 = MEDIUM | 20-49 = HIGH | 0-19 = CRITICAL
Data Confidence Score (compute alongside triage, 0-100):
Start at 0. Add points for each verified data point.
This measures HOW MUCH we could verify, not whether it's safe.
A high triage score with low confidence is MORE suspicious than a
moderate triage score with high confidence.
Verification points (+):
[ ] +15 Source code is open and verified on block explorer
[ ] +15 GoPlus token scan completed (not N/A or UNAVAILABLE)
[ ] +10 At least 1 audit report publicly available
[ ] +10 Multisig configuration verified on-chain (Safe API or Squads)
[ ] +10 Timelock duration verified on-chain or in docs
[ ] +10 Team identities publicly known (doxxed)
[ ] +10 Insurance fund size publicly disclosed
[ ] +5 Bug bounty program details publicly listed
[ ] +5 Governance process documented
[ ] +5 Oracle provider(s) confirmed
[ ] +5 Incident response plan published
[ ] +5 SOC 2 Type II or ISO 27001 certification verified
[ ] +5 Published key management policy (HSM, MPC, key ceremony)
[ ] +5 Regular penetration testing disclosed (infrastructure-level)
[ ] +5 Bridge DVN/verifier configuration publicly documented (if cross-chain)
Report both scores together: "Triage: 75/100 | Confidence: 40/100"
Interpretation:
80-100 = HIGH confidence (most claims verified)
50-79 = MEDIUM confidence (significant gaps remain)
0-49 = LOW confidence (most claims unverified -- treat score with skepticism)
- Quantitative baselines (compute these for the report):
Insurance Fund / TVL ratio(healthy: >5%, concerning: <1%)Audit Coverage Score:
Sum across all known audits:
1.0 per audit less than 1 year old
0.5 per audit 1-2 years old
0.25 per audit older than 2 years
Risk thresholds: >= 3.0 = LOW | 1.5-2.99 = MEDIUM | < 1.5 = HIGH
Governance decentralization score: timelock hours + multisig threshold ratio + signer doxxingTVL trend: 7d, 30d, 90d change percentagesGoPlus risk flags: count of HIGH + MEDIUM flags from token security check
Step 1: Gather Protocol Information
Use web search to collect the following. Run these specific queries (replace {protocol} with the protocol name):
- Basic info: chain, TVL, token, launch date, team (doxxed or anon)
- Search:
"{protocol}" DeFi protocol overview
- Protocol type: lending, DEX, perps, yield, bridge, etc.
- Architecture: key smart contracts, upgrade mechanisms
- Search:
"{protocol}" docs architecture OR contracts OR "smart contract"
- Security incidents:
- Search:
"{protocol}" exploit OR hack OR vulnerability OR "security incident" - Search:
"{protocol}" site:rekt.news - Search:
"{protocol}" post-mortem OR postmortem
- Audit discovery — run these sources IN ORDER and deduplicate. Missing an audit is a common failure mode (e.g., Apyx publishes Quantstamp/Certora/Zellic reports at
docs.apyx.fi/resources/auditsthat generic web search often misses). Do not stop at the first source — cross-check all four.
a. DeFiLlama protocol payload (authoritative if populated). From the Step 0 data, parse these fields:
curl -s 'https://api.llama.fi/protocol/{slug}' | jq '{audits, audit_note, audit_links}'
audits: numeric count (0/1/2/3)audit_note: free-text summaryaudit_links: array of URLs to audit PDFs
b. Protocol documentation — try these paths explicitly (substitute the protocol's docs domain; many use docs.{domain} or {domain}/docs):
https://docs.{domain}/audits
https://docs.{domain}/resources/audits
https://docs.{domain}/security/audits
https://docs.{domain}/security
https://{domain}/audits
https://{domain}/security
Use WebFetch to pull each candidate page. Many protocols list audits here that are not indexed on DeFiLlama. Record firm name, date, and PDF URL for each.
c. GitHub audits folder — check the protocol's main contracts repo for an audits/ or /audit/ directory:
https://github.com/{org}/{repo}/tree/main/audits
https://github.com/{org}/audits
https://github.com/{org}/{repo}-audits
Trail of Bits, ConsenSys Diligence, OpenZeppelin, Zellic, Spearbit, Cantina commonly drop PDFs here.
d. Web search fallback (only after a/b/c are exhausted):
- Search:
"{protocol}" audit report site:github.com - Search:
"{protocol}" audit filetype:pdf - Search:
site:code4rena.com "{protocol}"(contest audits) - Search:
site:sherlock.xyz "{protocol}"(contest audits)
For each discovered audit, record: firm, date, scope/commit hash (if cited in the report), and source (DeFiLlama / docs / GitHub / search). If DeFiLlama's count differs from what you found in b/c, use your discovered list as authoritative and note the DeFiLlama gap under Information Gaps.
- Governance and admin configuration:
- Search:
"{protocol}" multisig OR timelock OR governance OR "admin key"
- Bug bounty:
- Search:
"{protocol}" site:immunefi.com
- Peer comparison: identify 2-3 comparable protocols for benchmarking. Selection criteria:
- Same category (e.g., lending vs lending, DEX vs DEX, perps vs perps)
- Similar TVL tier: within 5x of each other (e.g., $1B protocol compared to $200M-$5B peers, not $50M or $50B)
- Prefer same chain when possible, but cross-chain is acceptable if same-chain peers are unavailable
- Prefer well-known protocols with established security track records as at least one peer (provides a "gold standard" benchmark)
- Never compare against the protocol's own forks (e.g., don't compare Aave V3 to Aave V2)
Also check DeFiLlama for current TVL and TVL trend data.
Step 2: Governance & Admin Key Analysis
Evaluate the following and assign risk ratings (LOW / MEDIUM / HIGH / CRITICAL).
Do NOT use compound ratings like "LOW-MEDIUM" -- pick exactly one level per category.
2.1 Admin Key Surface Area
- What can the admin key do? (pause, upgrade, change params, drain)
- Is there a multisig? What is the threshold (e.g., 3/5)?
- Is there a timelock on admin actions? How long?
- Can admin list new collateral / markets without timelock?
- Can admin change oracle sources?
- Can admin modify withdrawal limits or risk parameters?
- Are multisig signers doxxed or anonymous?
Timelock bypass detection (critical -- a timelock is only as strong as its bypass):
- Does any role (emergency multisig, security council, guardian) bypass the timelock?
- What powers does the bypass role have? (pause-only is LOW risk; full upgrade/drain is HIGH)
- Is the bypass role itself behind a multisig? What threshold?
- Are there on-chain constraints on what the bypass role can do, or is it trust-based?
- Example: "48h timelock with a 3/5 emergency multisig that can only pause" = LOW risk. "48h timelock with a 2/3 security council that can upgrade" = HIGH risk.
2.2 Upgrade Mechanism
- Are contracts upgradeable (proxy pattern)?
- Who controls upgrades?
- Is there a timelock on upgrades?
- Has the protocol ever done an emergency upgrade?
2.3 Governance Process
- On-chain vs off-chain governance?
- Minimum voting period?
- Quorum requirements?
- Can governance be bypassed via Security Council or emergency multisig?
2.4 Token Concentration & Whale Risk (if on-chain governance)
- What percentage of voting supply do the top 5 holders control?
- Are top holders contracts (treasury, staking, vesting) or EOAs?
- Can a single whale meet quorum or pass a proposal unilaterally?
- Is there vote delegation, and how concentrated is delegated power?
- Cross-reference GoPlus
holdersdata if available from Step 0
Step 3: Oracle & Price Feed Analysis
3.1 Oracle Architecture
- Which oracle providers? (Pyth, Chainlink, custom, TWAP)
- Single oracle or multi-source?
- Fallback mechanism if oracle fails?
- Can admin override oracle source?
3.2 Collateral / Market Listing
- How are new assets listed? (governance vote, admin action, permissionless)
- Is there liquidity depth requirement for collateral?
- Are there automated checks on price feed quality?
- Can low-liquidity tokens be used as collateral?
3.3 Price Manipulation Resistance
- TWAP window length (if applicable)
- Circuit breaker for abnormal price movements?
- Maximum collateral factor for volatile assets?
Step 4: Economic Mechanism Analysis
4.1 Liquidation Mechanism
- How does liquidation work?
- Is there a liquidation delay or buffer?
- Are liquidators incentivized sufficiently?
- What happens during extreme market conditions?
4.2 Bad Debt Handling
- Insurance fund size relative to TVL?
- Socialized loss mechanism?
- Historical bad debt events?
4.3 Interest Rate / Funding Rate Model
- Is the model well-tested?
- Are there edge cases that could cause extreme rates?
- Can rates be manipulated?
4.4 Withdrawal & Deposit Limits
- Are there rate limits on withdrawals?
- Can limits be changed by admin?
- Is there a hard cap that even admin cannot override?
4.5 Collateral Source Risk (lending / CDP / money-market protocols only)
Skip for non-lending protocols (DEX, perps without external collateral, single-asset vaults).
The Kelp incident showed that a lending protocol's risk is dominated by the worst collateral it accepts, not the average. A single LRT, bridge token, or synthetic asset depeg can create bad debt that exceeds the insurance fund, even if every other collateral is pristine. Step 7.3 covers the inverse (this protocol's token used as collateral elsewhere); 4.5 covers collateral accepted into this protocol.
4.5.1 Inventory Accepted Collateral
For each enabled collateral asset, record:- Asset symbol, contract address, current TVL deposited, current borrow against it
- Asset category: native (ETH, BTC, stablecoin issued on-chain), LRT (rsETH, weETH, ezETH, pufETH), bridge/wrapped (any token whose backing lives on a different chain or in a custodian), synthetic (USDe, USDX, eUSD)
- Issuer / source protocol (e.g., Kelp for rsETH, EtherFi for weETH, Renzo for ezETH)
- Underlying messaging or bridge layer if applicable (LayerZero, Wormhole, Axelar, native bridge)
4.5.2 Per-Asset Exposure Caps
- Is there a hard supply cap (
supplyCap) per collateral, enforced in code? - Is there a borrow cap per asset?
- Can caps be raised without a timelock?
- Largest asset's deposited TVL as a % of total collateral TVL (concentration ratio)
4.5.3 Shared Bridge / Issuer Concentration
Multiple LRTs and synthetic assets may appear diversified but share the same bridge layer or issuer. Identify:- All collaterals that ride the same bridge provider (e.g., rsETH + weETH + ezETH all on LayerZero)
- All collaterals from the same issuer or its corporate group
- Combined exposure across the shared dependency as a % of total collateral TVL
- This combined number is the realistic worst-case loss from a single bridge or issuer failure -- treat it as one position, not many.
4.5.4 Insurance vs. Largest Exposure
- Largest single-collateral exposure (or largest shared-bridge / shared-issuer cluster from 4.5.3), in USD
- Insurance fund / safety module size, in USD
- This absolute-dollar comparison supersedes the "Insurance Fund / TVL %" rule for lending protocols. A 2% Insurance/TVL ratio is meaningless if a single asset is 30% of collateral.
- The insurance vs. exposure delta is an INPUT to the 4.5.5 rating ladder below — do NOT also rate it independently here, otherwise the same condition is counted twice (once in 4.5.4, once in 4.5.5).
4.5.5 Rating Ladder (binding for sub-category A.5)
Apply rows top-to-bottom; the first matching row is the rating. Thresholds use the largest single-asset exposure OR the largest shared-bridge / shared-issuer cluster size (USD) from 4.5.3, whichever is greater.
"Per-asset cap" qualifier: a cap counts only if it is binding — supplyCap < 20% of total collateral TVL. A 99%-of-TVL cap is treated as no cap.
| Rating | Conditions (all must hold for the row) |
|---|---|
| CRITICAL | Largest exposure > 30% of collateral AND insurance < that exposure AND (no per-asset rate limit AND no oracle circuit breaker on that collateral). Missing only one of the two protections → falls through to HIGH. |
| HIGH | Any of: (a) LRT/bridge/synthetic collateral exists without a binding per-asset cap (regardless of % — ungated growth is the risk), (b) largest exposure > 10% of collateral AND insurance < largest exposure, (c) shared-bridge/shared-issuer cluster size (USD) > insurance, (d) single native asset > 50% of collateral AND insurance < that exposure |
| MEDIUM | Either: (i) some bridge/LRT/synthetic collateral exists, every such asset has a binding per-asset cap, AND insurance ≥ largest exposure; OR (ii) all collateral is native but a single asset > 50% of collateral AND insurance ≥ largest exposure (concentrated-but-insured native pool) |
| LOW | All collateral is native (ETH, BTC, on-chain stablecoins), no single asset > 50% of collateral, AND insurance ≥ largest exposure |
Notes:
- The CRITICAL row requires BOTH protections missing (no rate limit AND no circuit breaker) on top of the >30% / underinsured conditions; missing exactly one protection stays at HIGH. This is the intentional reading of the AND.
- A protocol with a single native asset (e.g., wstETH-dominant) at >50% of collateral and insurance < that exposure is HIGH via row (d), not LOW.
- Sub-10% LRT/bridge/synthetic with no binding cap still rates HIGH via row (a) — small uncapped positions can grow.
- Cross-check findings here against the Kelp-type pattern checklist in Step 9; A.5 conditions and the Kelp-type indicators must agree, otherwise revisit one or the other.
Step 5: Smart Contract Security
5.1 Audit History
- How many audits? By whom?
- When was the last audit?
- Were critical findings fixed?
- Has the code changed significantly since last audit?
5.2 Bug Bounty
- Active bug bounty program?
- Maximum payout?
- Scope coverage?
5.3 Battle Testing
- How long has the protocol been live?
- Peak TVL handled?
- Any past exploits or near-misses?
- Open source code?
5.4 Source Code Review
If the protocol's smart contracts are open source (GitHub or verified on block explorer), perform a targeted source code review. This is NOT a full line-by-line audit — it focuses on verifying governance claims from Step 2 and detecting high-impact vulnerability patterns.
Skip this step if: contracts are closed-source AND not verified on any block explorer.
5.4.1 Obtain Source Code
Try these sources in order:
- Etherscan/block explorer: Fetch verified source from the chain's block explorer. For proxy contracts, fetch BOTH the proxy and implementation source.
# Etherscan (Ethereum)
curl -s "https://api.etherscan.io/api?module=contract&action=getsourcecode&address=<address>&apikey=<key>"
# Arbiscan (Arbitrum)
curl -s "https://api.arbiscan.io/api?module=contract&action=getsourcecode&address=<address>&apikey=<key>"
- GitHub: Search for the protocol's contract repository.
- Search:
"{protocol}" smart contracts site:github.com - Common patterns:
github.com/{org}/contracts,github.com/{org}/{protocol}-core
- Audit reports: If no public repo exists, check if audit reports contain code snippets or contract interfaces.
Record source availability: "Full source (GitHub + verified)", "Partial (verified on explorer only)", "Closed source".
5.4.2 Admin & Access Control Patterns
Search the source code for these patterns. Each finding should cross-reference the governance analysis from Step 2.
Owner/admin functions — search for functions that can modify critical state:
Search for: onlyOwner, onlyAdmin, onlyRole, onlyGovernance, _checkRole, requiresAuth
Search for: function set*, function update*, function change*, function pause, function unpause
Search for: function upgrade*, function migrate*, _authorizeUpgrade
For each admin function found, document:
- What it can do (change parameters, pause, upgrade, drain)
- What access control guards it (Ownable, AccessControl role, custom modifier)
- Whether it has a timelock wrapper or can be called directly
- Whether it matches claims from Step 2 (e.g., "team claims 48h timelock" — verify the timelock is actually enforced in code)
Proxy upgrade pattern — identify which pattern is used:
Search for: TransparentUpgradeableProxy, UUPSUpgradeable, _authorizeUpgrade, ERC1967Upgrade
Search for: Diamond, DiamondCut, LibDiamond (EIP-2535)
Search for: Beacon, BeaconProxy, UpgradeableBeacon- UUPS: upgrade logic is in the implementation — check
_authorizeUpgradefor access control - Transparent: upgrade logic is in the ProxyAdmin — check who owns ProxyAdmin
- Diamond: facets can be added/removed — check who controls
diamondCut
Emergency/bypass roles — verify claims about emergency powers:
Search for: emergency, guardian, pauser, EMERGENCY_ROLE, GUARDIAN_ROLE
Search for: delay, setDelay, updateDelay, minDelay, getMinDelay- Does the emergency role only pause, or can it upgrade/drain?
- Can the timelock delay be set to 0? By whom?
5.4.3 Common Vulnerability Patterns
Scan for these high-impact patterns:
Reentrancy:
Search for: .call{value:, .call(, (bool success,) =
Check: Is there a reentrancy guard (nonReentrant, ReentrancyGuard)?
Check: Does the contract follow checks-effects-interactions pattern?Flag if: external calls are made before state updates, AND no reentrancy guard exists.
Oracle manipulation:
Search for: getPrice, latestAnswer, latestRoundData, getUnderlyingPrice, twap, TWAP
Search for: slot0 (Uniswap V3 spot price — manipulable via flash loans)Flag if: spot price is used without TWAP protection, OR single oracle with no fallback.
Flash loan attack surface:
Search for: flashLoan, flashMint, IERC3156, IFlashLoanReceiver
Check: Can flash-loaned tokens be used as collateral or voting power in the same transaction?
Unchecked return values:
Search for: .transfer(, .send(, .approve(
Check: Are return values checked? (SafeERC20 usage = good)
Centralization in token contract:
Search for: mint(, burn(, _mint(, _burn(, blacklist, freeze, pause
Check: Who can call these? Is there a cap on minting?
5.4.4 Cross-Reference with Governance Claims
This is the most important part. Compare what the code actually does vs. what the team/docs claim:
| Claim from Step 2 | Code verification | Match? |
|---|---|---|
| "48h timelock on upgrades" | Check: is timelock enforced in proxy admin? Can it be bypassed? | |
| "3/5 multisig controls admin" | Check: is the admin address actually the claimed multisig? | |
| "Oracle uses Chainlink" | Check: is Chainlink actually imported and used? Any fallback? | |
| "Insurance fund covers bad debt" | Check: does the liquidation flow actually transfer to insurance fund? | |
| "Immutable core contracts" | Check: are there really no upgrade functions? No selfdestruct? | |
Record any discrepancies as HIGH or CRITICAL findings.
5.4.5 Report Format
Add to the Smart Contract Security section of the risk report:
#### Source Code Review
**Source availability**: [Full/Partial/Closed]
**Contracts reviewed**: [list of key contracts and addresses]
**Admin function inventory**:
| Function | Contract | Access Control | Timelock? | Impact |
|----------|----------|---------------|-----------|--------|
**Vulnerability scan**:
| Pattern | Found? | Details | Severity |
|---------|--------|---------|----------|
**Governance claim verification**:
| Claim | Code evidence | Verified? |
|-------|-------------|-----------|
**Source code review conclusion**: [summary of findings]
5.5 Audited vs Deployed Drift
The most commonly ignored smart-contract risk is that audited code is NOT what is running in production. This can happen in several ways:
- The team commissions an audit, then deploys a NEWER version that was never re-audited.
- A proxy's implementation is upgraded after the audit without a new audit round.
- The audit covers only a subset of the deployed contracts.
- The audit was performed on a commit that was never deployed (vaporware audit).
This sub-step cross-references what was audited against what is running. Skip only if (a) no audits exist OR (b) all contracts are closed-source AND not verified on any explorer.
5.5.1 Extract Audit Scope
From each audit report discovered in Step 1.5, record:
- Firm and date
- Commit hash / git tag reviewed (most reports state this in the Scope or Methodology section)
- Contracts in scope (list of file names or addresses)
- Findings status (how many fixed vs acknowledged vs unresolved)
If a report does NOT cite a commit or tag, flag as HIGH info gap — the audit cannot be independently reproduced or re-verified.
5.5.2 Post-Audit Upgrade Detection
For each known proxy contract on an EVM chain, check the implementation's deployment timestamp against
<!-- truncated -->
SKILL.md source
---
name: defi-risk-analysis
description: Analyze a DeFi protocol's risk profile across smart contract, off-chain, and track-record dimensions. Use when the user wants a risk analysis of a DeFi project, to check protocol security, or to as...
---
# defi-risk-analysis
Analyze a DeFi protocol's risk profile across smart contract, off-chain, and track-record dimensions. Use when the user wants a risk analysis of a DeFi project, to check protocol security, or to assess risk. Trigger words include "risk analysis", "analyze protocol", "audit defi", "check security", "defi risk", "protocol vulnerability", "is it safe".
---
name: defi-risk-analysis
description: Analyze a DeFi protocol's risk profile across smart contract, off-chain, and track-record dimensions. Use when the user wants a risk analysis of a DeFi project, to check protocol security, or to assess risk. Trigger words include "risk analysis", "analyze protocol", "audit defi", "check security", "defi risk", "protocol vulnerability", "is it safe".
version: 2.1.0
allowed-tools: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch
metadata:
openclaw:
requires:
bins:
- curl
- jq
optional_bins:
- solana
---
# DeFi Risk Analysis Skill
Perform a comprehensive risk analysis of a DeFi protocol. This skill systematically evaluates smart contract risk, off-chain risk (governance, team, operations), and track record (historical incidents, battle-testing, response capability).
This is a structured **risk analysis**, NOT a formal smart contract audit — it reviews publicly available information and on-chain state to surface risk signals. Formal audits require line-by-line code review by professional auditing firms.
## Input
The user provides one or more of:
- Protocol name (e.g., "Aave", "Drift", "GMX")
- Protocol website or DeFiLlama URL
- Contract addresses or chain
## Workflow
### Step 0: Quick Triage (Red Flag Scan)
Before deep analysis, run a quick triage to decide analysis priority:
1. **DeFiLlama data check**:
First, resolve the protocol name to the correct DeFiLlama slug (slugs are non-obvious, e.g., "maker" not "sky", "pancakeswap" not "pancake-swap"):
```bash
# Fetch all protocols and fuzzy-match by name
curl -s 'https://api.llama.fi/protocols' | jq -r '.[] | select(.name | test("{protocol}"; "i")) | "\(.slug) -- \(.name) -- TVL: \(.tvl)"'
```
If no match, try partial name or check the protocol's website for its DeFiLlama listing.
Then fetch full data with the resolved slug: `curl -s 'https://api.llama.fi/protocol/{slug}'` to get:
- Current TVL and TVL history (sharp drops = red flag)
- Number of audits listed
- Chain(s)
2. **GoPlus token security check**: If the protocol has a governance/utility token on an EVM chain, run `./scripts/goplus-check.sh token <chain_id> <contract_address>` or call the API directly:
```bash
curl -s "https://api.gopluslabs.io/api/v1/token_security/<chain_id>?contract_addresses=<address>"
```
Extract these red flags from the response:
- `is_honeypot = 1` -- token is a honeypot (CRITICAL)
- `honeypot_with_same_creator = 1` -- creator has deployed honeypots (CRITICAL)
- `is_open_source = 0` -- contract not verified (HIGH)
- `hidden_owner = 1` -- hidden ownership mechanism (HIGH)
- `owner_change_balance = 1` -- owner can modify balances (HIGH)
- `selfdestruct = 1` -- contract can self-destruct (HIGH)
- `can_take_back_ownership = 1` -- can reclaim ownership after renouncing (HIGH)
- `is_proxy = 1` -- upgradeable proxy (MEDIUM, cross-reference with Step 2)
- `is_mintable = 1` -- unlimited minting possible (MEDIUM)
- `slippage_modifiable = 1` -- owner can change tax/slippage (MEDIUM)
- `transfer_pausable = 1` -- transfers can be paused (MEDIUM)
- `is_blacklisted = 1` -- has blacklist functionality (MEDIUM)
Also note: `buy_tax`, `sell_tax`, `holder_count`, `lp_holders` (lock status), and `trust_list` status.
**Chain IDs**: 1=Ethereum, 56=BSC, 137=Polygon, 42161=Arbitrum, 10=Optimism, 43114=Avalanche, 8453=Base, 324=zkSync. Solana is NOT supported by GoPlus token security API.
**Solana token fallback**: GoPlus does not support Solana SPL tokens. For Solana protocols, use these alternatives instead:
- **RugCheck**: `curl -s 'https://api.rugcheck.xyz/v1/tokens/{mint_address}/report'` -- returns risk score, mutable metadata, freeze authority, mint authority, top holders, LP lock status
- **Birdeye**: `curl -s -H 'X-API-KEY: public' 'https://public-api.birdeye.so/public/token_security?address={mint_address}'` -- holder concentration, LP info
- **Manual checks**: On Solana Explorer, verify: (1) mint authority (revoked = safer), (2) freeze authority (revoked = safer), (3) metadata mutability, (4) top holder concentration
Record the source as "RugCheck" or "Birdeye" instead of "GoPlus" in the report. If none of the alternatives return data, record "Solana Token Check: UNAVAILABLE" and note the gap.
**Error handling**: GoPlus is a free API with undocumented rate limits. If the API returns an error, empty result, or times out:
- Record "GoPlus: UNAVAILABLE" in the report rather than omitting the section
- Wait 5 seconds and retry once
- If still failing, proceed with the analysis without GoPlus data and note the gap in Information Gaps
3. **GoPlus address check** (optional): If specific admin/deployer addresses are known, check for malicious history:
```bash
curl -s "https://api.gopluslabs.io/api/v1/address_security/<address>?chain_id=<chain_id>"
```
Flags: `cybercrime`, `money_laundering`, `phishing_activities`, `stealing_attack`, `sanctioned`, `honeypot_related_address`, `malicious_mining_activities`, `number_of_malicious_contracts_created`.
4. **Immediate red flags** (any = escalate to CRITICAL triage):
- TVL = $0 or dropped >50% in 30 days
- No audits listed on DeFiLlama
- Protocol age < 6 months with TVL > $50M
- Anonymous team with no prior track record
- Closed-source contracts
- GoPlus: honeypot detected or creator has honeypot history
- GoPlus: hidden owner or owner can change balances
- GoPlus: admin/deployer address flagged as malicious
5. **Quick Triage Score** (compute for the report, 0-100):
```
Start at 100. Subtract EXACTLY the listed points for each flag that applies.
Do NOT adjust, round, or add mitigating bonuses -- the score is mechanical.
CRITICAL flags (-25 each):
[ ] GoPlus: is_honeypot = 1
[ ] GoPlus: honeypot_with_same_creator = 1
[ ] GoPlus: hidden_owner = 1
[ ] GoPlus: owner_change_balance = 1
[ ] TVL = $0
[ ] Admin/deployer address flagged as malicious
HIGH flags (-15 each):
[ ] Closed-source contracts (is_open_source = 0)
[ ] Zero audits listed on DeFiLlama
[ ] Anonymous team with no prior track record
[ ] GoPlus: selfdestruct = 1
[ ] GoPlus: can_take_back_ownership = 1
[ ] No multisig (single EOA admin key)
[ ] Single bridge provider for cross-chain deployments on 5+ chains (Kelp lesson)
[ ] Lending/CDP protocol accepts LRT, bridge token, or synthetic asset as collateral without a *binding* per-asset cap (supplyCap < 20% of total collateral TVL; see Step 4.5.5). This flag fires regardless of current % exposure -- ungated collateral can grow. Insurance-vs-largest-exposure is rated separately in Step 4.5 and must not also be flagged here.
MEDIUM flags (-8 each):
[ ] GoPlus: is_proxy = 1 AND no timelock on upgrades
[ ] GoPlus: is_mintable = 1
[ ] Protocol age < 6 months with TVL > $50M
[ ] TVL dropped > 30% in 90 days
[ ] Multisig threshold < 3 signers (e.g., 2/N)
[ ] GoPlus: slippage_modifiable = 1
[ ] GoPlus: transfer_pausable = 1
[ ] No third-party security certification (SOC 2 / ISO 27001 / equivalent) for off-chain operations
[ ] **This protocol's** bridge/wrapped/LRT token is accepted as collateral on 3+ external lending protocols without rate limits (issuer-side downstream-cascade risk; for the inverse — this protocol *accepting* such collateral — see Step 4.5 / the HIGH flag above)
LOW flags (-5 each):
[ ] No documented timelock on admin actions
[ ] No bug bounty program
[ ] Single oracle provider
[ ] GoPlus: is_blacklisted = 1
[ ] Insurance fund / TVL < 1% or undisclosed
[ ] Undisclosed multisig signer identities
[ ] DAO governance paused or dissolved
[ ] No published key management policy (HSM, MPC, key ceremony)
[ ] No disclosed penetration testing (infrastructure, not just smart contract audit)
[ ] Custodial dependency without disclosed custodian certification
Floor at 0. Score meaning:
80-100 = LOW risk | 50-79 = MEDIUM | 20-49 = HIGH | 0-19 = CRITICAL
```
**Data Confidence Score** (compute alongside triage, 0-100):
```
Start at 0. Add points for each verified data point.
This measures HOW MUCH we could verify, not whether it's safe.
A high triage score with low confidence is MORE suspicious than a
moderate triage score with high confidence.
Verification points (+):
[ ] +15 Source code is open and verified on block explorer
[ ] +15 GoPlus token scan completed (not N/A or UNAVAILABLE)
[ ] +10 At least 1 audit report publicly available
[ ] +10 Multisig configuration verified on-chain (Safe API or Squads)
[ ] +10 Timelock duration verified on-chain or in docs
[ ] +10 Team identities publicly known (doxxed)
[ ] +10 Insurance fund size publicly disclosed
[ ] +5 Bug bounty program details publicly listed
[ ] +5 Governance process documented
[ ] +5 Oracle provider(s) confirmed
[ ] +5 Incident response plan published
[ ] +5 SOC 2 Type II or ISO 27001 certification verified
[ ] +5 Published key management policy (HSM, MPC, key ceremony)
[ ] +5 Regular penetration testing disclosed (infrastructure-level)
[ ] +5 Bridge DVN/verifier configuration publicly documented (if cross-chain)
Report both scores together: "Triage: 75/100 | Confidence: 40/100"
Interpretation:
80-100 = HIGH confidence (most claims verified)
50-79 = MEDIUM confidence (significant gaps remain)
0-49 = LOW confidence (most claims unverified -- treat score with skepticism)
```
6. **Quantitative baselines** (compute these for the report):
- `Insurance Fund / TVL ratio` (healthy: >5%, concerning: <1%)
- `Audit Coverage Score`:
```
Sum across all known audits:
1.0 per audit less than 1 year old
0.5 per audit 1-2 years old
0.25 per audit older than 2 years
Risk thresholds: >= 3.0 = LOW | 1.5-2.99 = MEDIUM | < 1.5 = HIGH
```
- `Governance decentralization score`: timelock hours + multisig threshold ratio + signer doxxing
- `TVL trend`: 7d, 30d, 90d change percentages
- `GoPlus risk flags`: count of HIGH + MEDIUM flags from token security check
### Step 1: Gather Protocol Information
Use web search to collect the following. Run these specific queries (replace `{protocol}` with the protocol name):
1. **Basic info**: chain, TVL, token, launch date, team (doxxed or anon)
- Search: `"{protocol}" DeFi protocol overview`
2. **Protocol type**: lending, DEX, perps, yield, bridge, etc.
3. **Architecture**: key smart contracts, upgrade mechanisms
- Search: `"{protocol}" docs architecture OR contracts OR "smart contract"`
4. **Security incidents**:
- Search: `"{protocol}" exploit OR hack OR vulnerability OR "security incident"`
- Search: `"{protocol}" site:rekt.news`
- Search: `"{protocol}" post-mortem OR postmortem`
5. **Audit discovery** — run these sources IN ORDER and deduplicate. Missing an audit is a common failure mode (e.g., Apyx publishes Quantstamp/Certora/Zellic reports at `docs.apyx.fi/resources/audits` that generic web search often misses). Do not stop at the first source — cross-check all four.
a. **DeFiLlama protocol payload** (authoritative if populated). From the Step 0 data, parse these fields:
```bash
curl -s 'https://api.llama.fi/protocol/{slug}' | jq '{audits, audit_note, audit_links}'
```
- `audits`: numeric count (0/1/2/3)
- `audit_note`: free-text summary
- `audit_links`: array of URLs to audit PDFs
b. **Protocol documentation** — try these paths explicitly (substitute the protocol's docs domain; many use `docs.{domain}` or `{domain}/docs`):
```
https://docs.{domain}/audits
https://docs.{domain}/resources/audits
https://docs.{domain}/security/audits
https://docs.{domain}/security
https://{domain}/audits
https://{domain}/security
```
Use WebFetch to pull each candidate page. Many protocols list audits here that are not indexed on DeFiLlama. Record firm name, date, and PDF URL for each.
c. **GitHub audits folder** — check the protocol's main contracts repo for an `audits/` or `/audit/` directory:
```
https://github.com/{org}/{repo}/tree/main/audits
https://github.com/{org}/audits
https://github.com/{org}/{repo}-audits
```
Trail of Bits, ConsenSys Diligence, OpenZeppelin, Zellic, Spearbit, Cantina commonly drop PDFs here.
d. **Web search fallback** (only after a/b/c are exhausted):
- Search: `"{protocol}" audit report site:github.com`
- Search: `"{protocol}" audit filetype:pdf`
- Search: `site:code4rena.com "{protocol}"` (contest audits)
- Search: `site:sherlock.xyz "{protocol}"` (contest audits)
For each discovered audit, record: firm, date, scope/commit hash (if cited in the report), and source (DeFiLlama / docs / GitHub / search). If DeFiLlama's count differs from what you found in b/c, use your discovered list as authoritative and note the DeFiLlama gap under Information Gaps.
6. **Governance and admin configuration**:
- Search: `"{protocol}" multisig OR timelock OR governance OR "admin key"`
7. **Bug bounty**:
- Search: `"{protocol}" site:immunefi.com`
8. **Peer comparison**: identify 2-3 comparable protocols for benchmarking. Selection criteria:
- **Same category** (e.g., lending vs lending, DEX vs DEX, perps vs perps)
- **Similar TVL tier**: within 5x of each other (e.g., $1B protocol compared to $200M-$5B peers, not $50M or $50B)
- **Prefer same chain** when possible, but cross-chain is acceptable if same-chain peers are unavailable
- **Prefer well-known protocols** with established security track records as at least one peer (provides a "gold standard" benchmark)
- **Never compare against the protocol's own forks** (e.g., don't compare Aave V3 to Aave V2)
Also check DeFiLlama for current TVL and TVL trend data.
### Step 2: Governance & Admin Key Analysis
Evaluate the following and assign risk ratings (LOW / MEDIUM / HIGH / CRITICAL).
Do NOT use compound ratings like "LOW-MEDIUM" -- pick exactly one level per category.
#### 2.1 Admin Key Surface Area
- What can the admin key do? (pause, upgrade, change params, drain)
- Is there a multisig? What is the threshold (e.g., 3/5)?
- Is there a timelock on admin actions? How long?
- Can admin list new collateral / markets without timelock?
- Can admin change oracle sources?
- Can admin modify withdrawal limits or risk parameters?
- Are multisig signers doxxed or anonymous?
**Timelock bypass detection** (critical -- a timelock is only as strong as its bypass):
- Does any role (emergency multisig, security council, guardian) bypass the timelock?
- What powers does the bypass role have? (pause-only is LOW risk; full upgrade/drain is HIGH)
- Is the bypass role itself behind a multisig? What threshold?
- Are there on-chain constraints on what the bypass role can do, or is it trust-based?
- Example: "48h timelock with a 3/5 emergency multisig that can only pause" = LOW risk. "48h timelock with a 2/3 security council that can upgrade" = HIGH risk.
#### 2.2 Upgrade Mechanism
- Are contracts upgradeable (proxy pattern)?
- Who controls upgrades?
- Is there a timelock on upgrades?
- Has the protocol ever done an emergency upgrade?
#### 2.3 Governance Process
- On-chain vs off-chain governance?
- Minimum voting period?
- Quorum requirements?
- Can governance be bypassed via Security Council or emergency multisig?
#### 2.4 Token Concentration & Whale Risk (if on-chain governance)
- What percentage of voting supply do the top 5 holders control?
- Are top holders contracts (treasury, staking, vesting) or EOAs?
- Can a single whale meet quorum or pass a proposal unilaterally?
- Is there vote delegation, and how concentrated is delegated power?
- Cross-reference GoPlus `holders` data if available from Step 0
### Step 3: Oracle & Price Feed Analysis
#### 3.1 Oracle Architecture
- Which oracle providers? (Pyth, Chainlink, custom, TWAP)
- Single oracle or multi-source?
- Fallback mechanism if oracle fails?
- Can admin override oracle source?
#### 3.2 Collateral / Market Listing
- How are new assets listed? (governance vote, admin action, permissionless)
- Is there liquidity depth requirement for collateral?
- Are there automated checks on price feed quality?
- Can low-liquidity tokens be used as collateral?
#### 3.3 Price Manipulation Resistance
- TWAP window length (if applicable)
- Circuit breaker for abnormal price movements?
- Maximum collateral factor for volatile assets?
### Step 4: Economic Mechanism Analysis
#### 4.1 Liquidation Mechanism
- How does liquidation work?
- Is there a liquidation delay or buffer?
- Are liquidators incentivized sufficiently?
- What happens during extreme market conditions?
#### 4.2 Bad Debt Handling
- Insurance fund size relative to TVL?
- Socialized loss mechanism?
- Historical bad debt events?
#### 4.3 Interest Rate / Funding Rate Model
- Is the model well-tested?
- Are there edge cases that could cause extreme rates?
- Can rates be manipulated?
#### 4.4 Withdrawal & Deposit Limits
- Are there rate limits on withdrawals?
- Can limits be changed by admin?
- Is there a hard cap that even admin cannot override?
#### 4.5 Collateral Source Risk (lending / CDP / money-market protocols only)
Skip for non-lending protocols (DEX, perps without external collateral, single-asset vaults).
The Kelp incident showed that a lending protocol's risk is dominated by the *worst* collateral it accepts, not the average. A single LRT, bridge token, or synthetic asset depeg can create bad debt that exceeds the insurance fund, even if every other collateral is pristine. Step 7.3 covers the inverse (this protocol's token used as collateral elsewhere); 4.5 covers collateral *accepted into* this protocol.
##### 4.5.1 Inventory Accepted Collateral
For each enabled collateral asset, record:
- Asset symbol, contract address, current TVL deposited, current borrow against it
- Asset category: native (ETH, BTC, stablecoin issued on-chain), LRT (rsETH, weETH, ezETH, pufETH), bridge/wrapped (any token whose backing lives on a different chain or in a custodian), synthetic (USDe, USDX, eUSD)
- Issuer / source protocol (e.g., Kelp for rsETH, EtherFi for weETH, Renzo for ezETH)
- Underlying messaging or bridge layer if applicable (LayerZero, Wormhole, Axelar, native bridge)
##### 4.5.2 Per-Asset Exposure Caps
- Is there a hard supply cap (`supplyCap`) per collateral, enforced in code?
- Is there a borrow cap per asset?
- Can caps be raised without a timelock?
- Largest asset's deposited TVL as a % of total collateral TVL (concentration ratio)
##### 4.5.3 Shared Bridge / Issuer Concentration
Multiple LRTs and synthetic assets may *appear* diversified but share the same bridge layer or issuer. Identify:
- All collaterals that ride the same bridge provider (e.g., rsETH + weETH + ezETH all on LayerZero)
- All collaterals from the same issuer or its corporate group
- Combined exposure across the shared dependency as a % of total collateral TVL
- This combined number is the realistic worst-case loss from a single bridge or issuer failure -- treat it as one position, not many.
##### 4.5.4 Insurance vs. Largest Exposure
- Largest single-collateral exposure (or largest shared-bridge / shared-issuer cluster from 4.5.3), in USD
- Insurance fund / safety module size, in USD
- This absolute-dollar comparison supersedes the "Insurance Fund / TVL %" rule for lending protocols. A 2% Insurance/TVL ratio is meaningless if a single asset is 30% of collateral.
- The insurance vs. exposure delta is an INPUT to the 4.5.5 rating ladder below — do NOT also rate it independently here, otherwise the same condition is counted twice (once in 4.5.4, once in 4.5.5).
##### 4.5.5 Rating Ladder (binding for sub-category A.5)
Apply rows top-to-bottom; the first matching row is the rating. Thresholds use the largest single-asset exposure OR the largest shared-bridge / shared-issuer cluster size (USD) from 4.5.3, whichever is greater.
**"Per-asset cap" qualifier**: a cap counts only if it is *binding* — supplyCap < 20% of total collateral TVL. A 99%-of-TVL cap is treated as no cap.
| Rating | Conditions (all must hold for the row) |
|---|---|
| CRITICAL | Largest exposure > 30% of collateral AND insurance < that exposure AND (no per-asset rate limit AND no oracle circuit breaker on that collateral). Missing only one of the two protections → falls through to HIGH. |
| HIGH | Any of: (a) LRT/bridge/synthetic collateral exists without a binding per-asset cap (regardless of % — ungated growth is the risk), (b) largest exposure > 10% of collateral AND insurance < largest exposure, (c) shared-bridge/shared-issuer cluster size (USD) > insurance, (d) single native asset > 50% of collateral AND insurance < that exposure |
| MEDIUM | Either: (i) some bridge/LRT/synthetic collateral exists, every such asset has a binding per-asset cap, AND insurance ≥ largest exposure; OR (ii) all collateral is native but a single asset > 50% of collateral AND insurance ≥ largest exposure (concentrated-but-insured native pool) |
| LOW | All collateral is native (ETH, BTC, on-chain stablecoins), no single asset > 50% of collateral, AND insurance ≥ largest exposure |
Notes:
- The CRITICAL row requires BOTH protections missing (no rate limit AND no circuit breaker) on top of the >30% / underinsured conditions; missing exactly one protection stays at HIGH. This is the intentional reading of the AND.
- A protocol with a single native asset (e.g., wstETH-dominant) at >50% of collateral and insurance < that exposure is HIGH via row (d), not LOW.
- Sub-10% LRT/bridge/synthetic with no binding cap still rates HIGH via row (a) — small uncapped positions can grow.
- Cross-check findings here against the Kelp-type pattern checklist in Step 9; A.5 conditions and the Kelp-type indicators must agree, otherwise revisit one or the other.
### Step 5: Smart Contract Security
#### 5.1 Audit History
- How many audits? By whom?
- When was the last audit?
- Were critical findings fixed?
- Has the code changed significantly since last audit?
#### 5.2 Bug Bounty
- Active bug bounty program?
- Maximum payout?
- Scope coverage?
#### 5.3 Battle Testing
- How long has the protocol been live?
- Peak TVL handled?
- Any past exploits or near-misses?
- Open source code?
#### 5.4 Source Code Review
If the protocol's smart contracts are open source (GitHub or verified on block explorer), perform a targeted source code review. This is NOT a full line-by-line audit — it focuses on verifying governance claims from Step 2 and detecting high-impact vulnerability patterns.
**Skip this step if**: contracts are closed-source AND not verified on any block explorer.
##### 5.4.1 Obtain Source Code
Try these sources in order:
1. **Etherscan/block explorer**: Fetch verified source from the chain's block explorer. For proxy contracts, fetch BOTH the proxy and implementation source.
```bash
# Etherscan (Ethereum)
curl -s "https://api.etherscan.io/api?module=contract&action=getsourcecode&address=<address>&apikey=<key>"
# Arbiscan (Arbitrum)
curl -s "https://api.arbiscan.io/api?module=contract&action=getsourcecode&address=<address>&apikey=<key>"
```
2. **GitHub**: Search for the protocol's contract repository.
- Search: `"{protocol}" smart contracts site:github.com`
- Common patterns: `github.com/{org}/contracts`, `github.com/{org}/{protocol}-core`
3. **Audit reports**: If no public repo exists, check if audit reports contain code snippets or contract interfaces.
Record source availability: "Full source (GitHub + verified)", "Partial (verified on explorer only)", "Closed source".
##### 5.4.2 Admin & Access Control Patterns
Search the source code for these patterns. Each finding should cross-reference the governance analysis from Step 2.
**Owner/admin functions** — search for functions that can modify critical state:
```
Search for: onlyOwner, onlyAdmin, onlyRole, onlyGovernance, _checkRole, requiresAuth
Search for: function set*, function update*, function change*, function pause, function unpause
Search for: function upgrade*, function migrate*, _authorizeUpgrade
```
For each admin function found, document:
- What it can do (change parameters, pause, upgrade, drain)
- What access control guards it (Ownable, AccessControl role, custom modifier)
- Whether it has a timelock wrapper or can be called directly
- Whether it matches claims from Step 2 (e.g., "team claims 48h timelock" — verify the timelock is actually enforced in code)
**Proxy upgrade pattern** — identify which pattern is used:
```
Search for: TransparentUpgradeableProxy, UUPSUpgradeable, _authorizeUpgrade, ERC1967Upgrade
Search for: Diamond, DiamondCut, LibDiamond (EIP-2535)
Search for: Beacon, BeaconProxy, UpgradeableBeacon
```
- UUPS: upgrade logic is in the implementation — check `_authorizeUpgrade` for access control
- Transparent: upgrade logic is in the ProxyAdmin — check who owns ProxyAdmin
- Diamond: facets can be added/removed — check who controls `diamondCut`
**Emergency/bypass roles** — verify claims about emergency powers:
```
Search for: emergency, guardian, pauser, EMERGENCY_ROLE, GUARDIAN_ROLE
Search for: delay, setDelay, updateDelay, minDelay, getMinDelay
```
- Does the emergency role only pause, or can it upgrade/drain?
- Can the timelock delay be set to 0? By whom?
##### 5.4.3 Common Vulnerability Patterns
Scan for these high-impact patterns:
**Reentrancy**:
```
Search for: .call{value:, .call(, (bool success,) =
Check: Is there a reentrancy guard (nonReentrant, ReentrancyGuard)?
Check: Does the contract follow checks-effects-interactions pattern?
```
Flag if: external calls are made before state updates, AND no reentrancy guard exists.
**Oracle manipulation**:
```
Search for: getPrice, latestAnswer, latestRoundData, getUnderlyingPrice, twap, TWAP
Search for: slot0 (Uniswap V3 spot price — manipulable via flash loans)
```
Flag if: spot price is used without TWAP protection, OR single oracle with no fallback.
**Flash loan attack surface**:
```
Search for: flashLoan, flashMint, IERC3156, IFlashLoanReceiver
Check: Can flash-loaned tokens be used as collateral or voting power in the same transaction?
```
**Unchecked return values**:
```
Search for: .transfer(, .send(, .approve(
Check: Are return values checked? (SafeERC20 usage = good)
```
**Centralization in token contract**:
```
Search for: mint(, burn(, _mint(, _burn(, blacklist, freeze, pause
Check: Who can call these? Is there a cap on minting?
```
##### 5.4.4 Cross-Reference with Governance Claims
This is the most important part. Compare what the code actually does vs. what the team/docs claim:
| Claim from Step 2 | Code verification | Match? |
|---|---|---|
| "48h timelock on upgrades" | Check: is timelock enforced in proxy admin? Can it be bypassed? | |
| "3/5 multisig controls admin" | Check: is the admin address actually the claimed multisig? | |
| "Oracle uses Chainlink" | Check: is Chainlink actually imported and used? Any fallback? | |
| "Insurance fund covers bad debt" | Check: does the liquidation flow actually transfer to insurance fund? | |
| "Immutable core contracts" | Check: are there really no upgrade functions? No selfdestruct? | |
Record any discrepancies as HIGH or CRITICAL findings.
##### 5.4.5 Report Format
Add to the Smart Contract Security section of the risk report:
```
#### Source Code Review
**Source availability**: [Full/Partial/Closed]
**Contracts reviewed**: [list of key contracts and addresses]
**Admin function inventory**:
| Function | Contract | Access Control | Timelock? | Impact |
|----------|----------|---------------|-----------|--------|
**Vulnerability scan**:
| Pattern | Found? | Details | Severity |
|---------|--------|---------|----------|
**Governance claim verification**:
| Claim | Code evidence | Verified? |
|-------|-------------|-----------|
**Source code review conclusion**: [summary of findings]
```
#### 5.5 Audited vs Deployed Drift
The most commonly ignored smart-contract risk is that audited code is NOT what is running in production. This can happen in several ways:
- The team commissions an audit, then deploys a NEWER version that was never re-audited.
- A proxy's implementation is upgraded after the audit without a new audit round.
- The audit covers only a subset of the deployed contracts.
- The audit was performed on a commit that was never deployed (vaporware audit).
This sub-step cross-references what was audited against what is running. Skip only if (a) no audits exist OR (b) all contracts are closed-source AND not verified on any explorer.
##### 5.5.1 Extract Audit Scope
From each audit report discovered in Step 1.5, record:
- **Firm** and **date**
- **Commit hash / git tag** reviewed (most reports state this in the Scope or Methodology section)
- **Contracts in scope** (list of file names or addresses)
- **Findings status** (how many fixed vs acknowledged vs unresolved)
If a report does NOT cite a commit or tag, flag as HIGH info gap — the audit cannot be independently reproduced or re-verified.
##### 5.5.2 Post-Audit Upgrade Detection
For each known proxy contract on an EVM chain, check the implementation's deployment timestamp against
<!-- truncated -->
Related skills 6
caveman
Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, wenyan-lite, wenyan-full, wenyan-ultra. Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens", "be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested.
secure-linux-web-hosting
Use when setting up, hardening, or reviewing a cloud server for self-hosting, including DNS, SSH, firewalls, Nginx, static-site hosting, reverse-proxying an app, HTTPS with Let's Encrypt or ACME clients, safe HTTP-to-HTTPS redirects, or optional post-launch network tuning such as BBR.
readme-i18n
Use when the user wants to translate a repository README, make a repo multilingual, localize docs, add a language switcher, internationalize the README, or update localized README variants in a GitHub-style repository.
lark-shared
Use when first setting up lark-cli, running auth login, switching user/bot identity (--as), handling permission denied or scope errors, needing to update lark-cli, or seeing _notice in JSON output.
improve-codebase-architecture
Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable.
paper-context-resolver
Optional RigorPilot helper for README-first deep learning repo reproduction. Use only when the README and repository files leave a narrow reproduction-critical gap and the task is to resolve a specific paper detail such as dataset split, preprocessing, evaluation protocol, checkpoint mapping, or runtime assumption from primary paper sources while recording conflicts. Do not use for general paper summary, repo scanning, environment setup, command execution, title-only paper lookup, or replacin...