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
Key Services:
- Faucet Service (
backend/shared/services/faucet_service.go) - Distributes test USDC to users
- Rate limiting (24h cooldown per address)
-
Blockchain integration
-
Balance Service (
backend/shared/services/balance_service.go) - Queries user balances from blockchain
- Aggregates multi-token balances
-
SafeDecimal calculations
-
Investment Service (
backend/shared/services/canonical/investment_service.go) - Manages investment positions
- Strategy selection (5%, 10%, 20% APY)
-
Compound interest calculations
-
Withdrawal Service (
backend/shared/services/withdrawal_execution_service.go) - Processes withdrawal requests
- Admin approval workflow
-
Blockchain transaction execution
-
Auth Service (
backend/auth/service/jwt_mvp.go) - JWT token generation
- Web3 signature verification
- 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:
- Deploy to inactive environment (green)
- Run health checks
- Switch Nginx proxy
- Monitor new environment
- Rollback if issues detected
Security Architecture¶
Multiple Security Layers:
- Network Security:
- HTTPS/TLS 1.3
- Firewall rules (UFW)
-
CORS policies
-
Authentication:
- JWT tokens (HS256)
- Web3 wallet signatures
-
Admin/User role separation
-
Application Security:
- Input validation
- SQL parameterization
- Rate limiting
-
CSRF protection
-
Data Security:
- Encrypted connections
- SafeDecimal for financial operations
-
Audit logging
-
Smart Contract Security:
- OpenZeppelin libraries
- UUPS upgradeable pattern
- 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:
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:
Test Infrastructure: - Unit Tests: Go test framework - Integration Tests: Real backend + PostgreSQL - E2E Tests: Playwright + real blockchain - Smoke Tests: Critical path validation
Related Documentation¶
- Architecture Overview
- Backend Architecture
- Frontend Architecture
- Blockchain Integration
- Security Architecture
- Deployment Guide
📋 Метаданные¶
Версия: 2.4.82
Обновлено: 2025-10-21
Статус: Published