Skip to content

Latest commit

Β 

History

915 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

GasGuard: Automated Optimization Suite

License: MIT Ecosystem: Stellar

GasGuard is an open-source static analysis tool built to secure and optimize the Stellar ecosystem (Soroban), with extended support for Ethereum and Layer 2 networks. By identifying inefficient storage patterns and redundant operations during development, GasGuard enables developers to ship leaner code, reducing end-user transaction costs by an estimated 15-30%.


1. Executive Summary

In the high-stakes world of smart contracts, inefficient code is more than a nuisanceβ€”it's an expense. GasGuard analyzes codebases to find "gas-heavy" patterns before they reach the mainnet. Specifically optimized for Soroban's resource limits, it ensures that Stellar developers can maximize their contract's efficiency and reach.

2. The Problem

As Web3 scales, transaction costs remain a significant barrier to entry.

  • Legacy Patterns: Many developers use outdated coding patterns that result in "bloated" contracts.
  • Tooling Gap: Existing tools are often too complex for junior developers or lack native support for modern environments like Soroban or Optimism.
  • Resource Exhaustion: On Stellar, exceeding CPU or Ledger limits can cause contract failure; developers need early-warning systems to prevent this.

3. Key Features

  • πŸ” Static Analysis: Scans code for common gas-heavy patterns (e.g., inefficient loops, unoptimized storage slots).
  • πŸ’‘ Auto-Refactor Suggestions: Provides "Copy-Paste" ready code snippets to replace inefficient logic instantly.
  • πŸ€– CI/CD Integration: A dedicated GitHub Action that runs on every push, ensuring no "gas regressions" are introduced.
  • πŸ“š Educational Tooltips: Every suggestion includes a link to documentation explaining why the change saves money, fostering developer growth.
  • πŸ§ͺ Rule Testing Framework: Comprehensive testing utilities with input/output fixtures, snapshot testing, and assertion helpers for rule developers.
  • πŸ”¬ Policy Simulation Mode: Dry-run feature to preview policy violations before deployment with detailed violation reports and metrics.

4. Roadmap for this Wave

  • Phase 1: Complete the Core CLI tool for local developer use (Rust/Soroban focus).
  • Phase 2: Launch the GitHub Action Marketplace integration for automated PR reviews.
  • Phase 3: Establish a "Community Ruleset" allowing users to contribute new optimization patterns via Pull Requests.

5. Why GasGuard belongs in Drips Wave

  • Public Good: The core engine is 100% free and MIT-licensed to benefit the entire developer community.
  • Scalability: The modular design allows us to add support for 3 new languages (Rust, Vyper, Move) over the next 6 months.
  • Sustainability: We use Drips to "pass through" 15% of our funding to the foundational security libraries (like Slither or Cargo-Audit) that power our engine.

πŸ›  Project Structure (Monorepo)

GasGuard/
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ api/               # Nest.js backend handling remote scan requests
β”‚   └── api-service/       # Enhanced API service with database and E2E testing
β”œβ”€β”€ libs/
β”‚   └── engine/            # Core logic for parsing Rust, Solidity, and Vyper
β”œβ”€β”€ packages/
β”‚   └── rules/             # Library of optimization rules and logic
β”œβ”€β”€ .gitignore             # Optimized for Node.js and Rust
└── LICENSE                # MIT Licensed

πŸ” Dependency Provenance

GasGuard verifies the supply-chain provenance of all npm and Cargo dependencies on every CI run. Each dependency is checked to ensure it:

  • Resolves from a known, trusted registry (npmjs.com or crates.io).
  • Carries a strong integrity hash (sha512 for npm, SHA-256 for Cargo).
  • Does not use deprecated or weak hash algorithms.

Run the check locally with:

pnpm run provenance:check

See docs/DEPENDENCY_PROVENANCE.md for the full reference.


πŸ” Privilege Boundaries

GasGuard follows the principle of least privilege across all components. This section documents the trust boundaries, privilege levels, and security assumptions for each part of the system.

Trust Boundary Overview

Component Privilege Level Trust Boundary Notes
CLI (libs/engine) Local user Runs with invoking user's privileges No network access required; reads local files only
API (apps/api) Unprivileged service Public network boundary Rate-limited; no filesystem write access
API Service (apps/api-service) Unprivileged service Public network + DB boundary Scoped DB credentials; no shell execution
Rules (packages/rules) Sandboxed Executed in-process Must not perform I/O or network calls
CI/CD Action Repository-scoped GitHub Actions runner Read-only token by default; no secret exposure

Security Assumptions

  • No implicit trust between components. Each service validates inputs independently.
  • Secrets are never logged. API keys, tokens, and credentials are redacted from all log output.
  • Database access is least-privilege. Each service uses a dedicated role with only the permissions it requires.
  • Rule execution is pure. Optimization rules must be deterministic and side-effect free.
  • Network egress is restricted. Services only communicate with explicitly allowlisted upstreams.

Upstream & Cross-Component Dependencies

Dependency Purpose Privilege Impact
@nestjs/throttler Rate limiting Prevents abuse of public endpoints
PostgreSQL Audit log storage Append-only role; no DDL in runtime
Redis Rate-limit state Ephemeral; no PII stored
Hardhat (test only) Local chain simulation Never used in production
Cargo-Audit / Slither Security scanning Read-only analysis

Reporting a Privilege Issue

If you discover a privilege escalation or boundary violation, please follow the process in SECURITY.md and do not open a public issue.


πŸ›‘οΈ Rate Limiting

The public API includes IP-based rate limiting to protect against abuse and ensure fair usage.

Setting Value Description
Limit 10 requests Maximum requests per IP address
Window 60 seconds Time window for rate limit
Response HTTP 429 Returned when limit is exceeded

Rate limiting is implemented using @nestjs/throttler and applies globally to all public API endpoints.

Running the API

cd apps/api
npm install
npm run start

The API will be available at http://localhost:3000.

πŸ”Œ API Versioning

The GasGuard API uses NestJS built-in versioning with URI-based versioning strategy. All endpoints require a version prefix.

Versioning Strategy

  • Type: URI-based versioning
  • Current Version: v1
  • Format: All endpoints must include /v1/ prefix
  • Unversioned Requests: Return 404 Not Found

Example Endpoints

# βœ… Correct - Versioned endpoint
GET /v1/example

# ❌ Incorrect - Unversioned (returns 404)
GET /example

Adding New Controllers

When creating new controllers, always include the @Version('1') decorator:

import { Controller, Get, Version } from '@nestjs/common';

@Controller('users')
@Version('1')
export class UsersController {
  @Get()
  findAll() {
    // Accessible at GET /v1/users
  }
}

Configuration

Versioning is configured in apps/api/src/main.ts:

app.enableVersioning({
  type: VersioningType.URI,
  // No defaultVersion - unversioned requests return 404
});

This ensures all API consumers explicitly specify the version, making the API future-proof for version migrations.

πŸ§ͺ End-to-End Testing

GasGuard includes comprehensive end-to-end testing to ensure reliable gasless transaction flows across all services.

E2E Test Framework

  • Framework: Jest with Supertest for API testing
  • Blockchain: Hardhat local network for contract interactions
  • Services: Dockerized PostgreSQL, Redis, and mock RPC providers
  • Coverage: Full gasless transaction workflows and failure scenarios

Running E2E Tests

# Install dependencies
pnpm install

# Start test environment
docker-compose -f apps/api-service/docker-compose.e2e.yml up -d

# Run E2E tests
cd apps/api-service
pnpm run test:e2e

# Or run from root
pnpm run test:e2e

Test Structure

apps/api-service/test/
β”œβ”€β”€ e2e/                    # E2E test suites
β”‚   β”œβ”€β”€ basic-api.e2e-spec.ts
β”‚   β”œβ”€β”€ gasless-transaction.e2e-spec.ts
β”‚   β”œβ”€β”€ failure-scenarios.e2e-spec.ts
β”‚   └── contract-interaction.e2e-spec.ts
β”œβ”€β”€ utils/                  # Test utilities
β”‚   β”œβ”€β”€ test-helpers.ts
β”‚   └── blockchain-setup.ts
└── fixtures/               # Test data fixtures

For detailed information, see:

οΏ½ Audit Logging System

GasGuard includes a comprehensive audit logging system for enterprise compliance and accountability. The system tracks all critical actions including:

  • API Requests: Every endpoint access with status, latency, and requestor information
  • Key Management: API key creation, rotation, and revocation events
  • Gas Transactions: All gas transaction submissions and processing with chain context
  • Immutable Storage: Append-only logs with SHA256 integrity verification
  • Enterprise Reporting: CSV/JSON export, advanced filtering, and compliance reports

Key Features

  • βœ… Automatic HTTP request capture via interceptor
  • βœ… Multi-chain support (Ethereum, Solana, Stellar, etc.)
  • βœ… PostgreSQL storage with optimized indexing
  • βœ… RESTful API for querying and exporting logs
  • βœ… 70%+ test coverage with unit and E2E tests
  • βœ… Configurable retention policies

Access the Audit API

# Query logs with filtering
curl "http://localhost:3000/audit/logs?eventType=APIRequest&from=2024-02-01&to=2024-02-28"

# Export logs for compliance
curl -X POST "http://localhost:3000/audit/logs/export" \
  -H "Content-Type: application/json" \
  -d '{"format": "csv"}' > audit-logs.csv

For comprehensive documentation, see:

πŸ“Š Analyzer Coverage Reporting

GasGuard includes comprehensive analyzer coverage reporting to track how thoroughly your codebase is being analyzed and identify patterns not covered by any rules.

Key Features

  • βœ… Multiple report formats (text, JSON, HTML, Markdown)
  • βœ… Coverage metrics tracking (nodes analyzed vs. total nodes)
  • βœ… Uncovered pattern identification
  • βœ… Rule-by-rule coverage breakdown
  • βœ… Threshold checking for CI/CD pipelines
  • βœ… Beautiful interactive HTML reports

Quick Usage

import { CoverageReporter } from './src/reporting/coverage';
import { RuleCoverageAnalyzer } from './src/analysis/coverage';

// Track coverage during analysis
const analyzer = new RuleCoverageAnalyzer();
// ... perform analysis ...

// Generate report
const reporter = new CoverageReporter();
const reportData = reporter.createReportData(
  'MyProject',
  '1.0.0',
  analyzer.getMetrics(),
  10, 12, 1500
);

// Save HTML report
await reporter.saveReport(reportData, './reports/coverage.html', {
  format: 'html',
  includeUncoveredDetails: true,
  thresholdPercent: 85
});

CI/CD Integration

# Check coverage threshold in your pipeline
- name: Check Coverage
  run: |
    npm run analyze:coverage
    # Fails if coverage < 80%

For comprehensive documentation, see:

πŸš€ Getting Started

Prerequisites

  • Node.js 18+
  • Docker & Docker Compose
  • pnpm package manager
  • Rust toolchain (for core engine)

Installation

# Clone the repository
git clone https://github.com/your-username/GasGuard.git
cd GasGuard

# Install dependencies
pnpm install

# Run tests
pnpm run test

# Start the API
cd apps/api
npm run start:dev

🀝 Contributing

We welcome contributions! Please see our contributing guidelines for more details.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

About

GasGuard is an open-source static analysis suite for [Stellar/EVM] developers. Built with a scalable Nest.js backend, it provides real-time scanning for Rust, Solidity, and Vyper contracts. It identifies gas-heavy patterns and suggests automated refactors, reducing transaction costs by 15-30% while maintaining high auditability.

Resources

Security policy

Stars

12 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages