Skip to content

21tash/Smart-Contract-Risk-Scanner-MVP

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Smart Contract Risk Scanner

A professional-grade, open-source tool for analyzing Ethereum smart contracts for security risks and rug-pull indicators. Built with Next.js, TypeScript, and Solidity AST parsing.

🎯 What This Tool Does

This scanner performs automated static analysis on smart contracts to identify:

  • Ownership & Centralization Risks: Owner privileges, admin controls
  • Fund Control Risks: Withdrawal functions, emergency drains
  • Supply Control Risks: Minting capabilities, token creation
  • Transfer Restrictions: Blacklist mechanisms, pausable functionality
  • Upgradeability Risks: Proxy patterns, delegatecall usage
  • Critical Vulnerabilities: Self-destruct capabilities

The tool uses a combination of AST parsing and pattern matching to detect these risks, then calculates a normalized risk score (0-100) with detailed explanations.

πŸš€ Features

  • βœ… Dual Input Methods: Analyze by Ethereum address or upload .sol file
  • βœ… AST-Based Analysis: Uses @solidity-parser/parser for accurate detection
  • βœ… Advanced Risk Scoring: Context-aware scoring with combination bonuses
  • βœ… Dangerous Pattern Detection: Identifies risky combinations (mint+withdraw, etc.)
  • βœ… Professional Reports: Audit-style summaries with clear recommendations
  • βœ… No External APIs: Completely local, no LLM dependencies, $0 API costs
  • βœ… Contract Comparison: Compare contracts against reference implementations

πŸ“Š Risk Scoring System

Verdict Levels

  • LOW_RISK (0-20): Minimal risk indicators
  • ELEVATED_RISK (21-50): Moderate risk factors present
  • HIGH_RISK (51-80): Significant risk factors requiring caution
  • CRITICAL_RISK (81-100): Severe risk indicators, potential rug-pull

Scoring Methodology

  1. Base Score: Sum of individual finding contributions

    • CRITICAL: 35 points
    • HIGH: 20 points
    • MEDIUM: 10 points
    • LOW: 5 points
    • Each finding is weighted by confidence (0.0-1.0)
  2. Combination Bonuses (Synergy Risks):

    • mint + withdraw β†’ +10 risk (fund extraction risk)
    • mint + fee manipulation β†’ +5 risk
    • blacklist + pause β†’ +5 risk (transfer control)
    • owner + mint + withdraw β†’ +20 risk (auto-elevate to HIGH_RISK)
    • Multiple findings in same category β†’ +2 per additional finding
  3. Auto-Elevation Rules:

    • selfdestruct present β†’ Auto CRITICAL_RISK
    • owner + mint + withdraw β†’ Auto HIGH_RISK minimum
  4. Final Score: Normalized to 0-100 range

Owner Privilege Detection

The scanner uses intelligent owner detection:

  • Standard Ownable Pattern (LOW severity): Owner exists but no high-risk functions
  • High-Risk Owner (MEDIUM+ severity): Owner has dangerous capabilities (mint, withdraw, blacklist, pause, selfdestruct)

This avoids penalizing standard OpenZeppelin Ownable patterns while still flagging dangerous owner privileges.

πŸ—οΈ Architecture

smart-contract-scanner/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ page.tsx                 # Main UI (input & results)
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”œβ”€β”€ scan/route.ts        # Contract analysis endpoint
β”‚   β”‚   └── compare/route.ts     # Contract comparison endpoint
β”‚   └── layout.tsx
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ analyzer.ts              # Main analysis engine (AST + regex)
β”‚   β”œβ”€β”€ ast-analyzer.ts          # AST-based pattern detection
β”‚   β”œβ”€β”€ risk-scorer.ts           # Advanced risk scoring with synergies
β”‚   β”œβ”€β”€ ai-explainer.ts          # Deterministic explanation generator
β”‚   β”œβ”€β”€ contract-comparator.ts   # Contract comparison engine
β”‚   β”œβ”€β”€ risk-patterns.ts         # Regex patterns (fallback)
β”‚   └── etherscan.ts             # Etherscan API client (mock for POC)
β”œβ”€β”€ types/
β”‚   └── index.ts                 # TypeScript interfaces
└── package.json

πŸ› οΈ Installation

Prerequisites

  • Node.js 18+
  • npm or yarn

Setup

# Clone the repository
git clone <your-repo-url>
cd smart-contract-scanner

# Install dependencies
npm install

# Run development server
npm run dev

Open http://localhost:3000 in your browser.

Build for Production

npm run build
npm start

πŸ“– Usage

Web UI

  1. Navigate to the application
  2. Choose input method:
    • Contract Address: Enter Ethereum address (e.g., 0x1234...)
    • Upload File: Upload a .sol file
  3. Click "Scan Contract"
  4. Review the risk assessment report

API Endpoints

Scan Contract

POST /api/scan
Content-Type: application/json

{
  "input": "contract source code or address",
  "isAddress": false,
  "useAdvancedScoring": true
}

Response:

{
  "contract_name": "ExampleToken",
  "risk_score": 65.5,
  "verdict": "HIGH_RISK",
  "findings": [...],
  "summary": "...",
  "scoreBreakdown": {
    "totalScore": 65.5,
    "baseScore": 55,
    "synergyScore": 10.5,
    "synergies": {
      "mintWithdrawCombo": 10,
      "ownerMintWithdrawCombo": 0.5
    }
  }
}

Compare Contracts

POST /api/compare
Content-Type: application/json

{
  "targetContract": "contract source",
  "referenceContract": "reference contract source",
  "targetIsAddress": false,
  "referenceIsAddress": false
}

πŸ” How Risk Scoring Works

Example: High-Risk Contract

Findings:

  • Mint function (HIGH severity) β†’ 20 points
  • Withdraw function (HIGH severity) β†’ 20 points
  • Owner privileges with high-risk functions (MEDIUM severity) β†’ 10 points

Base Score: 50 points

Combination Bonuses:

  • Mint + Withdraw combo β†’ +10 points
  • Owner + Mint + Withdraw combo β†’ +20 points

Total Score: 80 points β†’ HIGH_RISK

Example: Standard Ownable Contract

Findings:

  • Owner privileges, no high-risk functions (LOW severity) β†’ 5 points

Base Score: 5 points

Combination Bonuses: None

Total Score: 5 points β†’ LOW_RISK

🎨 Risk Categories

Findings are grouped into categories:

  • Ownership: Owner/admin controls
  • Funds Control: Withdrawal functions, emergency drains
  • Supply Control: Minting capabilities
  • Transfer Restrictions: Blacklist, pause mechanisms
  • Upgradeability: Proxy patterns, upgradeable contracts
  • Critical: Self-destruct, critical vulnerabilities

⚠️ Important Disclaimers

This tool is for informational purposes only.

  • ⚠️ Not Financial Advice: Results should not be considered financial advice
  • ⚠️ Not a Guarantee: Low risk score does not guarantee safety
  • ⚠️ Automated Analysis: This is pattern-based detection, not a full security audit
  • ⚠️ Always Verify: Always conduct your own research and consider professional audits
  • ⚠️ No Liability: Use at your own risk

πŸ”’ Security Considerations

For production deployment:

  1. Rate Limiting: Implement rate limits on API endpoints
  2. Input Validation: Validate all addresses and file uploads
  3. Sanitization: Sanitize file uploads (no arbitrary code execution)
  4. API Keys: Store Etherscan API keys in environment variables
  5. CORS: Configure CORS appropriately
  6. Error Handling: Don't expose internal errors to users

🚧 Roadmap

Phase 1 (Current)

  • βœ… AST-based analysis
  • βœ… Advanced risk scoring
  • βœ… Combination detection
  • βœ… Contract comparison

Phase 2 (Planned)

  • πŸ”„ Real Etherscan API integration
  • πŸ”„ Multi-chain support (BSC, Polygon, Arbitrum)
  • πŸ”„ Historical scan tracking
  • πŸ”„ Export reports (PDF, JSON)

Phase 3 (Future)

  • πŸ”„ User accounts & scan history
  • πŸ”„ API access for developers
  • πŸ”„ Slither/Mythril integration
  • πŸ”„ Real-time monitoring alerts

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

πŸ“ License

MIT License - see LICENSE file for details

πŸ™ Acknowledgments

πŸ“§ Support

For issues, questions, or contributions, please open an issue on GitHub.


Remember: This tool is a starting point for due diligence, not a replacement for professional security audits. Always verify contracts independently before interacting with them.

About

Ethereum smart contract security scanner using AST analysis and advanced risk scoring to detect rug-pull and control risks.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages