PRISM MEV Platform - Complete Documentation

πŸš€ Overview

The PRISM MEV Platform is a high-performance MEV arbitrage system with integrated observability and counter-MEV protection, designed for deployment on Solana. This documentation provides comprehensive guidance for deployment, configuration, and operation.

πŸ“‹ Table of Contents

  1. Quick Start
  2. Architecture Overview
  3. Observability Integration
  4. API Documentation
  5. Deployment Guides
  6. Configuration Reference
  7. Operational Procedures
  8. Troubleshooting

🏁 Quick Start

Prerequisites

  • Rust 1.70+ with Cargo
  • Docker and Docker Compose
  • Node.js 18+ (for Swagger UI)
  • Access to Solana RPC endpoints
  • HelioHost VPS or compatible hosting

Local Development Setup

# Clone the repository
git clone <repository-url>
cd prism-rust

# Build the workspace
cargo build --workspace

# Run tests
cargo test --workspace

# Start the main platform
cargo run --bin prism-mev-platform

# Start the arbitrage engine
cargo run --bin mev-arbitrage-engine

# Generate API documentation
make openapi-spec
# or: cargo run --bin generate_frontend_clients -- --write-spec-only

πŸ—οΈ Architecture Overview

Core Components

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    PRISM MEV Platform                       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚  Arbitrage      β”‚  β”‚  Counter-MEV    β”‚  β”‚ Observabilityβ”‚ β”‚
β”‚  β”‚  Engine         β”‚  β”‚  Protection     β”‚  β”‚ & Metrics    β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚  DEX Providers  β”‚  β”‚  Transaction    β”‚  β”‚ RPC Client   β”‚ β”‚
β”‚  β”‚ (Jupiter/Orca)  β”‚  β”‚  Builder        β”‚  β”‚ (Solana)     β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                β”‚
                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                 Observability Stack                         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚   OpenTelemetry β”‚  β”‚     Coroot      β”‚  β”‚   Grafana    β”‚ β”‚
β”‚  β”‚   (OTLP Export) β”‚  β”‚  (Observability β”‚  β”‚ (Optional)   β”‚ β”‚
β”‚  β”‚                 β”‚  β”‚    Backend)     β”‚  β”‚              β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key Features

  • Sub-100ms Arbitrage Detection: Real-time cross-DEX opportunity identification
  • Counter-MEV Protection: Sandwich attack detection and disruption
  • Multi-DEX Integration: Jupiter, Orca, Meteora support
  • Comprehensive Observability: OpenTelemetry + Coroot integration
  • Production-Ready: Full error handling, circuit breakers, rate limiting

πŸ“Š Observability Integration

OpenTelemetry + Coroot Stack

The platform includes comprehensive observability with:

  • Structured Logging: JSON-formatted logs with correlation IDs
  • Distributed Tracing: End-to-end request tracing with business context
  • Metrics Collection: Real-time performance and business metrics
  • OTLP Export: Direct integration with Coroot observability backend

Key Metrics Tracked

#![allow(unused)]
fn main() {
// Business Metrics
- arbitrage_opportunities_found_total
- arbitrage_opportunities_executed_total
- arbitrage_profit_total_lamports
- arbitrage_success_rate_percent

// Performance Metrics
- dex_quote_fetch_duration_ms
- transaction_build_duration_ms
- rpc_call_duration_ms
- circuit_breaker_state

// Error Metrics
- provider_errors_total
- transaction_errors_total
- rpc_errors_total
- counter_mev_detections_total
}

Tracing Context

All operations include structured tracing spans with:

#![allow(unused)]
fn main() {
// Arbitrage Operations
- cycle_id: UUID
- dex_path: Vec<DexType>
- input_amount: u64
- expected_profit: f64
- execution_time_ms: u64

// Counter-MEV Operations
- detection_type: String
- confidence_score: f64
- mitigation_strategy: String
- response_time_ms: u64
}

πŸ“š API Documentation

OpenAPI/Swagger Generation

Generate comprehensive API documentation:

# Generate OpenAPI specification
make openapi-spec

# Serve Swagger UI locally
npm install -g swagger-ui-serve
swagger-ui-serve docs/api/openapi.yaml

# Access at http://localhost:3000

Core API Endpoints

Health & Metrics

GET /health
GET /metrics
GET /api/v1/system/health
GET /api/v1/system/metrics
GET /api/v1/providers/health

Arbitrage Operations

POST /api/v1/arbitrage/analyze
GET  /api/v1/arbitrage/opportunities
POST /api/v1/arbitrage/execute
GET  /api/v1/arbitrage/history

Counter-MEV Protection

POST /api/v1/counter-mev/analyze
GET  /api/v1/counter-mev/detections
POST /api/v1/counter-mev/mitigate

Authentication

API endpoints use API key authentication:

x-api-key: your-api-key-here

πŸ“¦ Documentation Automation & CI

  • Build system: mdBook configured via book.toml with link checking enabled.
  • Local commands:
    • make docs-install-tools
    • make docs-serve
    • make docs-build
    • make docs-validate
  • Scripts: scripts/build-docs.sh, scripts/validate-docs.sh
  • CI: .github/workflows/docs.yml builds, validates, and deploys documentation to GitHub Pages on pushes to main.

πŸš€ Deployment Guides

Deployment Overview

Choose the method that fits your environment.

β†’ View Deployment Overview

Docker Compose Deployment

For local development and testing.

β†’ View Docker Compose Guide

Kubernetes Deployment

For cluster and production deployments.

β†’ View Kubernetes Guide

βš™οΈ Configuration Reference

Environment Variables

# Core Configuration
RUST_LOG=info
RUST_BACKTRACE=1

# RPC Configuration
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
SOLANA_RPC_TIMEOUT_MS=30000

# Observability Configuration
OTEL_EXPORTER_OTLP_ENDPOINT=http://coroot:8080/v1/traces
OTEL_SERVICE_NAME=prism-mev-platform
OTEL_SERVICE_VERSION=0.1.0
DEPLOYMENT_ENVIRONMENT=production

# DEX Provider Configuration
JUPITER_API_URL=https://quote-api.jup.ag/v6
ORCA_API_URL=https://api.orca.so
METEORA_API_URL=https://api.meteora.ag

# Security Configuration
API_KEY=your-secure-api-key
WALLET_PRIVATE_KEY_PATH=/secrets/wallet.key

Configuration Files

β†’ View Development Guide

πŸ”§ Operational Procedures

Monitoring & Alerting

Key Metrics to Monitor

  1. Arbitrage Performance

    • Opportunity detection rate
    • Execution success rate
    • Profit margins and totals
    • Latency percentiles
  2. System Health

    • RPC endpoint availability
    • DEX provider response times
    • Circuit breaker states
    • Memory and CPU usage
  3. Error Rates

    • Transaction failures
    • Provider timeouts
    • Network connectivity issues

Alert Thresholds

# Critical Alerts
- arbitrage_success_rate < 90%
- rpc_error_rate > 5%
- memory_usage > 85%
- profit_margin < 0.1%

# Warning Alerts
- dex_response_time > 500ms
- circuit_breaker_open = true
- queue_depth > 1000

Maintenance Procedures

Daily Operations

  1. Health Checks

    curl http://localhost:8080/health
    curl http://localhost:9090/metrics
    
  2. Log Review

    # Check error logs
    grep "ERROR" /var/log/prism-mev/*.log
    
    # Monitor profit/loss
    grep "profit" /var/log/prism-mev/*.log | tail -100
    
  3. Performance Review

    • Review Coroot dashboards
    • Check arbitrage success rates
    • Validate counter-MEV effectiveness

Weekly Operations

  1. Configuration Updates
  2. Security Patches
  3. Performance Optimization
  4. Backup Verification

β†’ View Operator Manual

πŸ› Troubleshooting

Common Issues

High Latency

  • Check RPC endpoint performance
  • Verify network connectivity
  • Review DEX provider response times
  • Check system resource usage

Transaction Failures

  • Validate wallet balance
  • Check priority fee settings
  • Review slippage tolerance
  • Verify DEX liquidity

Observability Issues

  • Confirm OTLP endpoint accessibility
  • Check Coroot backend status
  • Validate environment variables
  • Review log output for errors

β†’ View Troubleshooting in Operator Manual

πŸ“– Additional Resources

πŸ“ž Support

For technical support and questions:

  • Documentation: Check this comprehensive guide first
  • Issues: Create GitHub issues for bugs and feature requests
  • Discussions: Use GitHub Discussions for general questions
  • Security: Report security issues privately

Last Updated: 2025-01-06
Version: 0.1.0
Platform: Solana MEV Arbitrage System

User Guide

This section helps operators and developers use the PRISM MEV Platform effectively.

Getting Started

This guide provides a streamlined path to set up the documentation and explore the API.

Prerequisites

  • Rust toolchain (stable)
  • mdBook for docs: cargo install mdbook mdbook-linkcheck
  • Node.js (optional) for redoc-cli via npx

Build the Docs Locally

make docs-install-tools   # one-time
make docs-serve           # or: mdbook serve --open

API Overview

  • The platform exposes REST endpoints. Health check for providers is documented at: /api/v1/providers/health.
  • See API for details and OpenAPI usage.

Next Steps

Operator Manual

Operational guidance for running and maintaining a PRISM MEV instance.

Health and Monitoring

  • The providers health endpoint: GET /api/v1/providers/health
  • Integrate with your monitoring stack (Prometheus/Grafana) to scrape metrics if exposed by your deployment.

Routine Tasks

  • Validate docs and links: make docs-validate
  • Rebuild docs: make docs-build

Troubleshooting

  • Check logs for error context emitted by the application and middleware.
  • Validate configuration and environment variables.
  • Ensure network access to upstream providers.

Prerequisites and Planning

Before deploying to production, ensure the following minimums and preparation:

  • Infrastructure (HelioHost VPS)

    • Recommended: Ubuntu 22.04 LTS (or compatible), 2 vCPU, 4–8 GB RAM, 40+ GB SSD
    • Static public IPv4, root or sudo access
    • Open inbound ports: 80/tcp and 443/tcp for Coolify (reverse proxy & TLS)
    • Outbound egress to Solana RPC endpoints (HTTPS 443, WebSocket 443)
  • Domain & DNS

    • A/AAAA record(s) for your Coolify panel and app subdomains pointing to the VPS IP
    • If using Cloudflare, set SSL mode to "Full" and allow HTTP challenge on port 80 for initial certificate issuance
  • Software

    • Docker Engine and Docker Compose Plugin installed
    • Coolify (self‑hosted PaaS) installed on the VPS
  • Security & Secrets

    • Production RPC URLs and API keys ready (do not hardcode; store as Coolify secrets)
    • Any private keys required by the app are stored securely (hardware/remote signer preferred); never commit secrets
    • Enforce least privilege for integrations; rotate credentials on schedule
  • Operational Readiness

    • Define SLOs for latency and availability
    • Monitoring and alerting destinations determined (Pager/SMS/Email)
    • Backup and rollback strategy confirmed (Coolify backups, VPS snapshots)

Initial Deployment (Coolify on HelioHost VPS)

High‑level flow using Coolify’s official installation and UI. Adjust to match your environment and organization policies.

  1. Install Docker

    • Follow official Docker install for your OS; verify:
      docker --version && docker compose version
      
  2. Install Coolify

    • Follow Coolify’s official installation guide to run it via Docker/Compose on ports 80/443.
    • After start, access the Coolify dashboard via your configured domain/IP and create the admin account.
  3. Configure DNS and TLS

    • Point your chosen domain/subdomain(s) to the VPS IP via A/AAAA records.
    • In Coolify, enable TLS for the domain; ensure port 80 is reachable for HTTP challenge.
  4. Create an Application in Coolify

    • Source: connect to your Git repository for prism-rust or use a container image if prebuilt.
    • Choose build strategy (Dockerfile/Buildpacks). If using Dockerfile, ensure it exists at repo root or specify location in Coolify.
    • Set the service’s internal/external ports to match your app’s exposed port.
  5. Configure Environment Variables & Secrets

    • Add RPC endpoints, provider tokens, and any feature flags as Coolify environment variables/secrets.
    • Do not commit credentials to the repository.
  6. Deploy

    • Trigger the initial build and deployment from the Coolify UI.
    • Verify health:
      • GET /api/v1/providers/health responds 200
      • Application logs show no startup errors
  7. Verification Checklist

    • App reachable over HTTPS with valid certificate
    • Metrics/observability (if enabled by your deployment) are scraping and visible
    • Coolify shows deployment healthy and container(s) running

Daily Operations

  • Health Checks

    • Monitor GET /api/v1/providers/health for liveness.
    • Track error rates and latency in your monitoring stack if metrics are enabled.
  • Log Review

    • Use Coolify’s container log viewer for recent logs.
    • For deeper analysis, aggregate logs to your central system.
  • Deployment Management

    • Use Coolify to trigger rolling redeployments from main/trunk after reviews pass.
    • Keep an annotated change log to correlate deploys with metrics.
  • Docs Hygiene

    • make docs-validate on each PR affecting docs.
    • make docs-build to ensure publishability.

Maintenance Tasks

  • Upgrades

    • Application: Redeploy from updated repo or pull new image tag via Coolify.
    • Coolify platform: Follow Coolify’s upgrade notes; schedule maintenance window.
    • Docker Engine: Upgrade during off‑peak; restart Coolify afterward.
  • Secrets & Keys

    • Rotate API keys on a fixed cadence; update Coolify secrets and redeploy.
    • Validate access logs for unused credentials and revoke promptly.
  • Backups

    • Use Coolify’s backup features if configured, and/or VPS snapshots.
    • Test restores periodically in a staging environment.
  • Capacity Management

    • Monitor CPU/RAM/disk. Clean unused images/volumes during maintenance:
      docker system df
      docker image prune -a
      docker volume ls
      

Emergency Procedures

  • Roll Back a Bad Deploy

    • In Coolify, redeploy the previous successful commit or image tag.
    • If necessary, scale replicas to zero to halt traffic, then restore to last known good.
  • Disable External Traffic Quickly

    • Temporarily change DNS to a maintenance page or remove the A record.
    • If using Cloudflare, enable maintenance mode / block rules for the app subdomain.
  • Credential Compromise

    • Revoke affected keys immediately; rotate secrets in Coolify and redeploy.
    • Audit logs and increase monitoring thresholds.
  • Resource Exhaustion (CPU/RAM/Disk)

    • Scale down workload or temporarily disable non‑critical services.
    • Prune Docker artifacts to reclaim space; expand disk if needed.

Troubleshooting (Coolify on HelioHost VPS)

DNS/TLS Issues

  • Symptom: HTTPS certificate not issued; browser shows invalid certificate.
    • Ensure port 80 is open for HTTP challenge.
    • Verify DNS A/AAAA records point to the correct VPS IP and have propagated.
    • If using Cloudflare, set SSL mode to "Full" (not "Flexible"); temporarily disable "Always Use HTTPS" until issuance succeeds.

Port Conflicts

  • Symptom: Coolify or app fails to start; errors about ports 80/443 already in use.
    • Stop or remove other services (e.g., Apache/Nginx) binding 80/443.
    • Verify with:
      sudo lsof -i :80 -i :443
      

Low Memory / Build Failures

  • Symptom: Builds killed (OOM) or fail intermittently.
    • Add swap (e.g., 2–4 GB) on small VPS instances.
    • Use multi‑stage Docker builds or remote builders to reduce memory usage.

Disk Full

  • Symptom: no space left on device, image pulls/builds fail.
    • Clean Docker artifacts:
      docker system prune -a
      docker volume ls
      
    • Expand VPS disk or move Docker data to larger volume as needed.

App Unreachable Behind Coolify

  • Symptom: Coolify reports healthy, but app URL 404/502.
    • Check service port mapping in Coolify matches container’s exposed port.
    • Confirm health endpoint GET /api/v1/providers/health returns 200.
    • Inspect reverse proxy (Traefik) logs from Coolify.

Outbound RPC Connectivity Problems

  • Symptom: Timeouts reaching Solana RPC/WebSocket endpoints.
    • Verify firewall/eGRess policies allow HTTPS/WSS to provider domains.
    • Check DNS resolution on the VPS; ensure NTP time sync is healthy.

Coolify Platform Issues

  • Symptom: Coolify UI/agent not responding.
    • Restart Coolify containers via Docker and recheck logs.
    • Ensure VPS resources are sufficient; review Docker and system logs.

References

  • Coolify official documentation (installation, upgrades, backups)
  • Docker Engine and Compose official documentation
  • Your organization’s runbooks for secrets rotation, backup, and incident response

Deployment

Note: Prefer the per-app Coolify Compose files under deploy/coolify/ for production deployments. This docs/deployment/ folder is kept for human-readable guides and legacy stack examples.

Choose a deployment method that fits your environment:

Coolify on HelioHost VPS (Authoritative Per-App Setup)

Prefer the per-app Compose files under deploy/coolify/. The legacy monolithic stack in docs/deployment/coolify-config.yml is deprecated.

1) Prepare DNS

  • Create A records pointing to your VPS IP:
    • Docs: docs.digiplumb.dev (or your chosen docs domain)
    • API: api.<your-domain> β†’ set as API_DOMAIN_NAME
    • Jaeger UI (legacy, optional): jaeger.<your-domain> β†’ set as JAEGER_DOMAIN_NAME

2) Create apps in Coolify (one per component)

  • App: Docs β†’ Repository path: deploy/coolify/docs.compose.yml
    • Domain is currently hardcoded in the compose as docs.digiplumb.dev.
    • Health: /health
  • App: API β†’ Repository path: deploy/coolify/prism-api.compose.yml
    • Set env: API_DOMAIN_NAME, DATABASE_URL, REDIS_URL, RPC_URL, RUST_LOG, OTEL_EXPORTER_OTLP_ENDPOINT=http://coroot:8080/v1/traces
    • Health: /health
  • App: Observability (Jaeger - legacy) β†’ Repository path: deploy/coolify/legacy/observability.compose.yml (optional UI exposure)
    • Note: deploy/coolify/observability.compose.yml is an empty stub pointing to the legacy file above.
    • Set env: JAEGER_DOMAIN_NAME if exposing UI via Traefik
  • App: SurrealDB β†’ Repository path: deploy/coolify/surrealdb.compose.yml
    • Set env: SURREALDB_PASSWORD
  • App: Redis β†’ Repository path: deploy/coolify/redis.compose.yml
    • Set env: REDIS_PASSWORD

All routed apps attach to the external Docker network coolify for Traefik.

3) Traefik / TLS Notes

  • Entrypoints: http, https.
  • Cert resolver: letsencrypt.
  • ACME e-mail must be valid (e.g., your Gmail). Traefik handles certificate issuance automatically.
  • If you see ${VAR} literally in Traefik logs, Coolify did not interpolate label env vars. Hardcode the domain in the compose file (as done in deploy/coolify/docs.compose.yml).

4) Configure GitHub Actions secrets (docs deploy)

Set in GitHub repo β†’ Settings β†’ Secrets and variables β†’ Actions:

  • VPS_HOST (VPS hostname or IP)
  • VPS_USER (SSH user)
  • VPS_SSH_KEY (private key PEM; no passphrase or add support)
  • VPS_TARGET_PATH (e.g., /var/www/prism-docs)
  • DISCORD_WEBHOOK_URL (for notifications)

5) Deploy

  • In Coolify, deploy each app created above.
  • In GitHub, run workflow: β€œDocs Deploy to VPS” (or push to main).

6) Verify

  • Docs: https://<DOCS_DOMAIN_NAME> renders mdBook
  • Docs Health: GET https://<DOCS_DOMAIN_NAME>/health returns OK
  • API: GET https://<API_DOMAIN_NAME>/health returns 200 (valid cert)
  • Jaeger UI (legacy, optional): https://<JAEGER_DOMAIN_NAME>/ loads UI with valid cert
  • Discord channel shows workflow success/failure for docs deploy.

Notes

  • Caddy container serves /srv which is host-mounted from /var/www/prism-docs.
  • The docs workflow rsyncs the built book/ directory to VPS_TARGET_PATH.
  • StrictHostKeyChecking=no is used initially; consider pinning host key later for security.

Docker Compose Guide

This guide demonstrates how to run the PRISM MEV Platform using Docker Compose.

NOTE: This is a generic guide. For production on Coolify, prefer the per-app compose files under deploy/coolify/ (e.g., prism-api.compose.yml, coroot.compose.yml). The OTLP example below previously referenced coroot:8080/v1/traces which is not an OTLP collector. Use an actual OTLP collector (e.g., Jaeger all-in-one at http://jaeger:4318) or your OTel Collector endpoint.

Overview

  • Build an image for the service.
  • Configure environment variables.
  • Start services with Compose.

Production-focused configuration at a glance

  • Ports: API on 8080, Metrics/Health on 9090 (default metrics_port).
  • Health endpoints (from src/metrics/metrics_server.rs):
    • GET /health on metrics port (9090)
    • GET /api/v1/providers/health on metrics port (9090)
    • GET /metrics Prometheus text exposition on 9090
  • Key env vars (from real config):
    • MEV_MONITORING_METRICS_PORT=9090 (default)
    • MEV_OBSERVABILITY_PERCENTILES_ENABLED=true
    • OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318 (or your OTLP collector)
    • RUST_LOG=info or MEV_MONITORING_LOG_LEVEL=info, MEV_MONITORING_LOG_FORMAT=json
  • Security: run as non-root, read-only FS, drop capabilities; keep secrets out of env when possible.
  • Prometheus: scrape http://<host>:9090/metrics.

Example docker-compose.yml

version: "3.9"
services:
  prism:
    image: prism-mev:local
    build:
      context: .
      dockerfile: Dockerfile
    user: "10001:10001"           # run as non-root
    read_only: true                # read-only root filesystem
    cap_drop: ["ALL"]            # drop Linux capabilities
    environment:
      # Logging & monitoring
      RUST_LOG: info
      MEV_MONITORING_LOG_LEVEL: info
      MEV_MONITORING_LOG_FORMAT: "json"
      MEV_MONITORING_METRICS_PORT: 9090
      MEV_OBSERVABILITY_PERCENTILES_ENABLED: "true"
      # Tracing (OTLP/OTEL export)
      OTEL_EXPORTER_OTLP_ENDPOINT: "http://jaeger:4318"
      # Application config (examples β€” prefer docker secrets or files for sensitive values)
      # MEV_RPC_PRIMARY_URL: "https://api.mainnet-beta.solana.com"
      # MEV_PROVIDERS_JUPITER_BASE_URL: "https://quote-api.jup.ag"
      # MEV_WALLET_PUBKEY: "<your-wallet-pubkey>"
    volumes:
      - type: bind
        source: ./secrets
        target: /run/secrets
        read_only: true
    ports:
      - "8080:8080"   # API
      - "9090:9090"   # Metrics/Health
    healthcheck:
      test: ["CMD-SHELL", "curl -fsS http://localhost:9090/health || exit 1"]
      interval: 15s
      timeout: 5s
      retries: 5
    restart: unless-stopped
    deploy:
      resources:
        limits:
          cpus: "2.0"
          memory: 2g
        reservations:
          cpus: "1.0"
          memory: 1g
networks:
  default:
    driver: bridge

Steps

  1. Build image: docker compose build
  2. Start: docker compose up -d
  3. Check logs: docker compose logs -f prism
  4. Verify health: curl -f http://localhost:9090/health
  5. Verify providers health: curl -f http://localhost:9090/api/v1/providers/health
  6. Verify Prometheus metrics: curl -f http://localhost:9090/metrics | head

Notes

  • Adjust exposed port and env vars as needed.
  • For production, add proper volumes, secrets, and healthchecks.

Kubernetes Guide

This guide demonstrates how to deploy the PRISM MEV Platform to Kubernetes.

Example Manifest

apiVersion: apps/v1
kind: Deployment
metadata:
  name: prism
spec:
  replicas: 1
  selector:
    matchLabels:
      app: prism
  template:
    metadata:
      labels:
        app: prism
    spec:
      containers:
        - name: prism
          image: ghcr.io/your-org/prism-mev:latest
          imagePullPolicy: IfNotPresent
          env:
            - name: RUST_LOG
              value: info
          ports:
            - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: prism
spec:
  selector:
    app: prism
  ports:
    - name: http
      port: 80
      targetPort: 8080

Steps

  1. Build and push your image to a registry.
  2. Apply manifests: kubectl apply -f prism.yaml
  3. Verify service and logs.
  4. Access health endpoint: GET /api/v1/providers/health

Notes

  • Configure resources, probes, and secrets for production environments.

API

This section provides an overview of the PRISM MEV Platform API and how to consume the OpenAPI specification.

Health

  • GET /api/v1/providers/health β€” Returns providers health status.

OpenAPI

  • The OpenAPI spec is generated via utoipa from Rust types and handlers.

Generate the spec locally

You can produce fresh OpenAPI specs (JSON/YAML) into docs/api/ without building the full workspace:

make openapi-spec
# outputs:
#  - docs/api/openapi.yaml
#  - docs/api/openapi.json

Alternatively, call the binary directly (same effect):

cargo run --bin generate_frontend_clients -- --write-spec-only

Serve interactive docs (Swagger UI)

Run the lightweight docs server locally (no on-chain features needed):

make docs-server
# Swagger UI: http://localhost:8081/swagger-ui

Docs server endpoints for frontend consumption:

  • GET /api-docs/openapi.json
  • GET /api-docs/openapi.yaml
  • GET /api-docs/spec-version
  • GET /swagger-ui β€” Interactive UI

Local Testing

curl http://localhost:8080/api/v1/providers/health

Frontend Clients

Generate and sync TypeScript/JavaScript clients from the OpenAPI spec:

make clients-generate
FRONTEND_PATH=../your-frontend make clients-sync

Frontend Integration Guide

This section documents how frontend applications integrate with the PRISM MEV Platform.

  • OpenAPI spec endpoints: /api-docs/openapi.json, /api-docs/openapi.yaml
  • Interactive docs: /swagger-ui (Swagger UI)
  • Spec version: /api-docs/spec-version

Quick Start

  1. Generate OpenAPI spec + clients:
    make clients-generate
    
  2. Sync to your frontend repository:
    FRONTEND_PATH=../your-frontend make clients-sync
    
  3. In your frontend, import the generated TypeScript Axios client from src/api.

Live Docs Server

Run the docs server locally:

cargo run --bin docs_server --features off-chain -- 8081

Open http://localhost:8081/swagger-ui

Authentication

  • Use x-api-key header for endpoints requiring authentication.
  • Example:
    const client = axios.create({
      baseURL: process.env.NEXT_PUBLIC_API_BASE_URL,
      headers: { 'x-api-key': process.env.NEXT_PUBLIC_API_KEY! }
    })
    

Error Model

All API errors include a machine-readable code and human-friendly message suitable for UI display.

WebSocket Updates

The docs server reserves a channel for future live spec updates. Frontends may subscribe once available for hot reloading API schemas in dev mode.

TypeScript Client Guide

Installation

If you copy the generated client into your frontend:

# From the frontend repo
npm i axios

Usage

import { Configuration } from './api';
import { DefaultApi } from './api';

const config = new Configuration({
  basePath: process.env.NEXT_PUBLIC_API_BASE_URL,
  baseOptions: {
    headers: { 'x-api-key': process.env.NEXT_PUBLIC_API_KEY! },
    timeout: 10_000,
  }
});

const api = new DefaultApi(config);

async function health() {
  const res = await api.healthHandler();
  console.log(res.data);
}

health();

React Query Example

import { useQuery } from '@tanstack/react-query';
import { DefaultApi, Configuration } from './api';

const api = new DefaultApi(new Configuration({ basePath: '/api' }));

export function useSystemHealth() {
  return useQuery({
    queryKey: ['system-health'],
    queryFn: () => api.healthHandler().then(r => r.data),
    staleTime: 10_000,
  });
}

API Client Examples

Fetch Example

async function getMetrics() {
  const res = await fetch('/metrics');
  if (!res.ok) throw new Error('Failed to fetch metrics');
  return await res.text();
}

Axios with Retry

import axios from 'axios';
import axiosRetry from 'axios-retry';

const client = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_BASE_URL });
axiosRetry(client, { retries: 3, retryDelay: axiosRetry.exponentialDelay });

export async function getProvidersHealth() {
  const { data } = await client.get('/providers/health');
  return data;
}

Development

Resources for contributors and maintainers.

Contributing

Thank you for your interest in contributing!

Prerequisites

  • Rust (stable), Cargo
  • Recommended: rustup, clippy, rustfmt

Common Tasks

  • Format: cargo fmt --all
  • Lint: cargo clippy --all-targets --all-features -- -D warnings
  • Test: cargo test --workspace

Documentation

  • Install tools: cargo install mdbook mdbook-linkcheck
  • Build: make docs-build
  • Serve: make docs-serve
  • Validate links: make docs-validate

Binary Reference

This document lists and explains each binary target defined in Cargo.toml, including purpose, usage, options, configuration, and troubleshooting tips.

General tips:

  • Build & run: cargo run --release --bin <name> [-- <args>]
  • Discover binaries: check Cargo.toml [[bin]] entries or use shell completion with cargo run --bin <TAB>
  • Features: Off-chain binaries require the off-chain feature (enabled by default). On-chain binaries or special tools may require --features on-chain.
  • Configuration: Most binaries read from config/*.{toml,yaml,json} and environment variables with MEV_ prefix via Settings::load() in src/shared/config.rs.

Config overview (see src/shared/config.rs):

  • Providers: providers.jupiter|orca|meteora.{enabled,base_url,rate_limit_per_second,...}
  • Arbitrage: arbitrage.{min_profit_threshold,max_slippage_percent,scan_interval_ms,tokens,token_pairs,...}
  • RPC: rpc.{primary_url,fallback_urls,timeout_ms,max_retries,commitment,websocket_endpoint}
  • Transaction: transaction.{keypair_path,keypair_env_var,priority_fee_lamports,compute_unit_limit,confirmation_timeout_ms,max_retries}
  • Safety: safety.{trading_enabled,enable_dry_run,max_position_size_sol, ...}
  • Monitoring: monitoring.{enable_prometheus,metrics_port,log_level,log_format}

Default keypair env var is SOLANA_KEYPAIR (see TransactionConfig::default()), and all config keys are overridable via env with the MEV_ prefix (e.g., MEV_RPC__PRIMARY_URL).


mev-arbitrage-engine

  • Path: src/bin/mev_arbitrage_engine.rs
  • Purpose: Run the off-chain MEV arbitrage engine loop against enabled DEX providers, submit transactions, and expose Prometheus metrics.

Usage:

cargo run --release --bin mev-arbitrage-engine

Command-line options:

  • None. All behavior is controlled via configuration and env vars.

Configuration requirements:

  • Uses Settings::load() to load from config/default.*, environment-specific files, and MEV_ env vars.
  • Ensure at least one provider is enabled: providers.{jupiter,orca,meteora}.enabled = true.
  • RPC: rpc.primary_url must be reachable.
  • Safety: safety.trading_enabled and safety.enable_dry_run gate execution.
  • Monitoring: set monitoring.enable_prometheus = true and monitoring.metrics_port to expose metrics via start_metrics_server().

Troubleshooting:

  • "No providers enabled": Set one of providers.*.enabled = true.
  • RPC errors: Verify rpc.primary_url, fallback_urls, network connectivity, and rpc.timeout_ms.
  • Transaction submit failed: Check wallet balance, priority_fee_lamports, compute_unit_limit, and network congestion.
  • Immediate shutdown: Fatal errors (config, keypair, insufficient funds) trigger shutdown; check logs.

arbitrage-cli

  • Path: src/bin/arbitrage_cli.rs
  • Purpose: Lightweight CLI for one-shot arbitrage search and optional execution. Suitable for scripting and quick experiments.

Usage:

cargo run --release --bin arbitrage-cli -- \
  --wallet ~/.config/solana/id.json \
  --rpc-endpoint https://api.mainnet-beta.solana.com \
  --token-pairs SOL:USDC,SOL:USDT \
  --min-profit 0.001 \
  --max-slippage 1.0 \
  --timeout 30 \
  --max-opportunities 10 \
  --output-format pretty

Command-line options (see parse_args()):

  • --wallet, -w <KEYPAIR>: Required. Path to keypair file or base58 string.
  • --rpc-endpoint, -r <URL>: Solana RPC endpoint. Default: https://api.mainnet-beta.solana.com.
  • --token-pairs, -t <PAIRS>: Comma-separated pairs TOKEN1:TOKEN2[,...]. Default: SOL:USDC.
  • --min-profit, -p <PERCENTAGE>: Decimal percent threshold (e.g., 0.001 for 0.1%). Default: 0.001.
  • --max-slippage, -s <PERCENT>: Maximum allowed slippage. Default: 1.0.
  • --timeout <SECONDS>: Operation timeout. Default: 30.
  • --dry-run: Analyze without submitting transactions.
  • --output-format, -o <json|pretty>: Output format. Default: json.
  • --max-opportunities <COUNT>: Limit opportunities analyzed. Default: 10.

Configuration requirements:

  • Does not require config files. Providers use defaults; RPC and wallet come from CLI.
  • Wallet can be a file path (JSON) or base58 secret key string. Public key is derived and validated at runtime.

Troubleshooting:

  • Wallet loading failed: Ensure file path exists and is a valid Solana keypair, or base58 string is correct.
  • RPC health check failed: Verify endpoint URL and network; try a different RPC.
  • No opportunities found: Adjust --min-profit, --max-slippage, or token pairs.

mainnet-mev-system

  • Path: src/bin/mainnet_mev_system.rs
  • Purpose: Authentic mainnet MEV detection system with modes for detection-only, observability validation, or full run.

Usage:

cargo run --release --bin mainnet-mev-system -- \
  --mode detection \
  --min-profit 0.001 \
  --max-tps 100

# Enable real execution (DANGER: uses real SOL)
cargo run --release --bin mainnet-mev-system -- --mode full --enable-execution

Command-line options:

  • --mode <detection|observability|full>: Operation mode. Default: detection.
  • --enable-execution: Enable real transaction execution (safety countdown shown).
  • --min-profit <SOL>: Minimum profit in SOL. Default: 0.001.
  • --max-tps <TPS>: Max transactions per second processed. Default: 100.

Configuration requirements:

  • Uses Settings::default() internally; external config files are not required for this binary.

Troubleshooting:

  • Invalid mode: Use one of detection, observability, full.
  • Long startup: Real execution includes a safety countdown; wait or cancel with Ctrl+C.

production-mev-system

  • Path: src/bin/production_mev_system.rs
  • Purpose: Full production orchestrator with safety checks, observability, and graceful shutdown.

Usage:

# Safe (no real execution)
cargo run --release --bin production-mev-system

# Real execution
ENABLE_REAL_EXECUTION=true \
cargo run --release --bin production-mev-system

Command-line options:

  • None. Behavior is driven by configuration and env.

Environment & configuration:

  • Loads Settings::load() (config files + MEV_ envs).
  • Real execution is gated by ENABLE_REAL_EXECUTION=true env var.
  • Observability initialized via ObservabilityConfig::default().

Troubleshooting:

  • Init failed: Check config validity with config-test and verify RPC and provider URLs.
  • Real execution disabled: Set ENABLE_REAL_EXECUTION=true and confirm wallet funding and safety settings.

generate-openapi

This binary has been removed. Use generate_frontend_clients or the Makefile targets instead.


generate-frontend-clients

  • Path: src/bin/generate_frontend_clients.rs
  • Purpose: Generate OpenAPI specs into docs/api/ and optionally create frontend API clients using scripts/generate-frontend-clients.sh.

Usage:

# Write only the OpenAPI specs (no client generation)
cargo run --release --bin generate_frontend_clients -- --write-spec-only

# Or use the Makefile target
make openapi-spec

# Generate clients (requires openapi-generator or npx setup)
make clients-generate

Outputs:

  • docs/api/openapi.json
  • docs/api/openapi.yaml

Troubleshooting:

  • Client generation tool missing: Ensure openapi-generator is installed or available via npx.
  • Cannot write files: Ensure docs/ directory exists and is writable.

config-test

  • Path: src/bin/config_test.rs
  • Purpose: Validate loading and schema of a specific config file using Settings::load_from_file().

Usage:

cargo run --release --bin config-test -- ./config/development.yaml

Arguments:

  • <config_file>: Required. Path to a TOML/YAML/JSON configuration file.

Troubleshooting:

  • Validation failed: The tool prints detailed errors; fix URLs, numeric ranges, or provider settings.
  • File not found: Provide a correct path; relative to repo root or absolute.

test-yaml-config

  • Path: src/bin/test_yaml_config.rs
  • Purpose: Sanity-check YAML parsing into Settings and validate basic fields.

Usage:

cargo run --release --bin test-yaml-config

Behavior:

  • Reads test_config.yaml from current working directory.
  • Parses into Settings, validates, and performs a round-trip YAML serialization test.

Troubleshooting:

  • Missing file: Ensure test_config.yaml exists in the CWD.

simple-yaml-test

  • Path: src/bin/simple_yaml_test.rs
  • Purpose: Minimal serde_yaml round-trip example to verify YAML support.

Usage:

cargo run --release --bin simple-yaml-test

Troubleshooting:

  • None expected; prints serialized YAML and verifies round-trip integrity.

eidolon-mev-program

  • Path: src/bin/eidolon_mev_program.rs
  • Purpose: On-chain Anchor-based MEV program shell for deployment/tests.

Usage:

# Build/run with on-chain features
cargo run --release --features on-chain --bin eidolon-mev-program

Notes:

  • Without --features on-chain, the program prints a notice and exits.
  • When enabled, Anchor declare_id! and program entrypoints are compiled.

Feature flags summary

  • off-chain: Required for most runtime binaries. Enabled by default via features.default in Cargo.toml.
  • on-chain: Required only for on-chain program binaries.

Environment variables

  • MEV_*: Override any config key (e.g., MEV_RPC__PRIMARY_URL=https://...).
  • SOLANA_KEYPAIR: Default keypair env used by transaction signing (if transaction.keypair_path is not set).
  • ENABLE_REAL_EXECUTION: Enables real execution in production-mev-system.

Common troubleshooting

  • Provider URL invalid: Fix providers.*.base_url or disable the provider.
  • Metrics not exposed: Set monitoring.enable_prometheus=true and choose an open monitoring.metrics_port.
  • Permission denied writing docs: Run make openapi-spec from repo root or adjust file permissions.