Перейти к содержанию

System Architecture

Обзор

High-level system architecture документация для Saga DeFi Platform.

System Overview

Saga - это full-stack DeFi платформа построенная на следующих компонентах:

┌─────────────────────────────────────────────────────────────┐
│                    User Interface Layer                      │
│  ┌────────────────┐              ┌────────────────┐         │
│  │  User App      │              │  Admin App     │         │
│  │  (Next.js)     │              │  (Next.js)     │         │
│  │  Port 8080     │              │  Port 8080     │         │
│  └────────────────┘              └────────────────┘         │
└─────────────────────────────────┬───────────────────────────┘
                                  │ HTTPS/API calls
┌─────────────────────────────────▼───────────────────────────┐
│                    Backend Layer (Go)                        │
│  ┌──────────────────────────────────────────────────────┐   │
│  │              REST API Server (Chi Router)            │   │
│  │  • User endpoints (/api/user/*)                      │   │
│  │  • Admin endpoints (/api/admin/*)                    │   │
│  │  • Auth endpoints (/api/auth/*)                      │   │
│  │  • Blockchain endpoints (/api/blockchain/*)          │   │
│  └──────────────────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────────────────┐   │
│  │                Business Logic Layer                   │   │
│  │  • Faucet Service                                    │   │
│  │  • Balance Service                                   │   │
│  │  • Investment Service                                │   │
│  │  • Withdrawal Service                                │   │
│  │  • Auth Service (JWT)                                │   │
│  └──────────────────────────────────────────────────────┘   │
│  ┌──────────────────────────────────────────────────────┐   │
│  │              Data Access Layer                        │   │
│  │  • User Repository                                   │   │
│  │  • Transaction Repository                            │   │
│  │  • Investment Repository                             │   │
│  │  • Wallet Repository                                 │   │
│  └──────────────────────────────────────────────────────┘   │
└─────────────────────────────────┬───────────────────────────┘
                ┌─────────────────┼─────────────────┐
                │                 │                 │
┌───────────────▼──┐  ┌──────────▼────────┐  ┌────▼──────────┐
│   PostgreSQL     │  │  Blockchain Node  │  │  File System  │
│   Database       │  │  (Anvil/Foundry)  │  │  (Logs, etc.) │
│   Port 5432      │  │  Port 8545        │  │               │
└──────────────────┘  └───────────────────┘  └───────────────┘

Core Components

Frontend Applications

User App (/frontend/user-app): - Purpose: End-user interface for staking and investments - Framework: Next.js 14 (App Router) - Features: - MetaMask wallet connection - USDC staking (5%, 10%, 20% APY) - Balance monitoring - Transaction history - Investment management

Admin App (/frontend/admin-app): - Purpose: Administrative dashboard - Framework: Next.js 14 (App Router) - Features: - User management - Withdrawal approval - System monitoring - Investment oversight - Analytics dashboard

Shared Components (/frontend/shared): - UnifiedWeb3Provider (Wagmi configuration) - Reusable UI components - API client utilities - Type definitions

Backend Services

Architecture Pattern: Clean Architecture

Handler → Service → Repository → Database

Key Services:

  1. Faucet Service (backend/shared/services/faucet_service.go)
  2. Distributes test USDC to users
  3. Rate limiting (24h cooldown per address)
  4. Blockchain integration

  5. Balance Service (backend/shared/services/balance_service.go)

  6. Queries user balances from blockchain
  7. Aggregates multi-token balances
  8. SafeDecimal calculations

  9. Investment Service (backend/shared/services/canonical/investment_service.go)

  10. Manages investment positions
  11. Strategy selection (5%, 10%, 20% APY)
  12. Compound interest calculations

  13. Withdrawal Service (backend/shared/services/withdrawal_execution_service.go)

  14. Processes withdrawal requests
  15. Admin approval workflow
  16. Blockchain transaction execution

  17. Auth Service (backend/auth/service/jwt_mvp.go)

  18. JWT token generation
  19. Web3 signature verification
  20. Admin/User authorization

Database Layer

PostgreSQL Schema:

Core Tables: - users - User accounts (email, status) - wallets - Blockchain wallets (BIP44 compliant) - transactions - All financial operations (APPEND-ONLY) - investments - Investment positions - withdrawals - Withdrawal requests - sessions - JWT session tracking

Key Principles: - Foreign keys with CASCADE for referential integrity - Transactions are APPEND-ONLY (no deleted_at) - SafeDecimal compatibility (NUMERIC(78,0)) - Timestamps (created_at, updated_at) on all tables

Blockchain Layer

VPS Blockchain Node: - Technology: Anvil (Foundry) - Network: Saga Testnet (ChainID 1337) - RPC: http://188.42.218.164:8545 - Auto-mining: 12 second block time

Smart Contracts: - TestUSDC: ERC20 token (6 decimals) - StakingProtocol5/10/20: UUPS upgradeable staking (5%, 10%, 20% APY) - stUSDC5/10/20: Staking receipt tokens (18 decimals)

Data Flow

User Staking Flow

1. User connects MetaMask wallet
   └→ Frontend: useAccount() hook

2. User selects staking protocol (5%, 10%, 20%)
   └→ Frontend: useContractWrite()

3. User approves USDC spending
   └→ MetaMask: TestUSDC.approve()

4. User stakes USDC
   └→ MetaMask: StakingProtocol.stake()
   └→ Blockchain: Mint stTokens to user
   └→ Backend: Record investment in database

5. Backend queries updated balance
   └→ Blockchain: stToken.balanceOf()
   └→ Database: Update investment record

Withdrawal Flow

1. User requests withdrawal
   └→ Frontend: POST /api/withdrawals
   └→ Backend: Create withdrawal record (status: pending)

2. Admin reviews request
   └→ Admin App: GET /api/admin/withdrawals/pending
   └→ Admin App: Display withdrawal details

3. Admin approves withdrawal
   └→ Admin App: POST /api/admin/withdrawals/{id}/approve
   └→ Backend: Update status (pending → approved)
   └→ Backend: Queue blockchain transaction

4. Backend executes withdrawal
   └→ Withdrawal Service: Transfer USDC from master wallet
   └→ Blockchain: TestUSDC.transfer()
   └→ Backend: Update status (approved → completed)
   └→ Backend: Record transaction

5. User receives USDC
   └→ User's wallet balance updated on blockchain

🐳 Deployment Architecture

Docker Single Container

Architecture:

Docker Container (saga)
├── Go Backend Binary (/app/bin/saga)
├── Next.js Static Files (/app/static/)
│   ├── user-app/
│   └── admin-app/
├── Migrations (/app/migrations/)
├── Configuration (/app/config.yaml)
└── Environment Variables (/app/.env)

Benefits: - Single deployment unit - Consistent environment - Easy rollback - Simplified monitoring

Blue-Green Deployment

Production VPS (188.42.218.164):

/opt/saga/
├── blue/           # Active environment (port 8081)
├── green/          # Standby environment (port 8082)
├── shared/         # Shared resources
│   ├── logs/
│   └── deployment-state.json
└── code/           # Deployment scripts

Deployment Process:

  1. Deploy to inactive environment (green)
  2. Run health checks
  3. Switch Nginx proxy
  4. Monitor new environment
  5. Rollback if issues detected

Security Architecture

Multiple Security Layers:

  1. Network Security:
  2. HTTPS/TLS 1.3
  3. Firewall rules (UFW)
  4. CORS policies

  5. Authentication:

  6. JWT tokens (HS256)
  7. Web3 wallet signatures
  8. Admin/User role separation

  9. Application Security:

  10. Input validation
  11. SQL parameterization
  12. Rate limiting
  13. CSRF protection

  14. Data Security:

  15. Encrypted connections
  16. SafeDecimal for financial operations
  17. Audit logging

  18. Smart Contract Security:

  19. OpenZeppelin libraries
  20. UUPS upgradeable pattern
  21. Access control (Ownable)

Monitoring & Observability

Logging System

Canonical Logging (Go 1.21+ slog):

logger.InfoStructured("User action",
    "action", "stake",
    "user_id", userID,
    "amount", amount.String(),
    "strategy", strategyID,
)

Log Format:

time=2025-10-06T11:00:00Z level=INFO msg="User action" user_id=123 action=stake

Health Checks

Health Endpoint (/health):

{
  "status": "healthy",
  "version": "2.1.528",
  "database": "connected",
  "blockchain": "connected",
  "timestamp": "2025-10-06T11:00:00Z"
}

Metrics

System Metrics: - Request rate (req/s) - Response time (ms) - Error rate (%) - Active users - Transaction volume (USDC)

Configuration Management

UnifiedConfig System:

Environment Variables (highest priority)
.env file
config.yaml (generated from config/*.yaml)
Code defaults (lowest priority)

Modular Configuration: - config/network.yaml - Server, CORS - config/database.yaml - PostgreSQL - config/auth.yaml - JWT, admins - config/blockchain.yaml - RPC, contracts - config/testing.yaml - Test settings - config/monitoring.yaml - Logs, metrics - config/limits.yaml - Investment limits

Testing Architecture

Test Pyramid:

         E2E Tests (~30 minutes)
      Integration Tests (~3 minutes)
           Unit Tests (~30 seconds)

Test Infrastructure: - Unit Tests: Go test framework - Integration Tests: Real backend + PostgreSQL - E2E Tests: Playwright + real blockchain - Smoke Tests: Critical path validation




📋 Метаданные

Версия: 2.4.82

Обновлено: 2025-10-21

Статус: Published