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

Developer Onboarding Guide

Обзор

Complete onboarding guide для новых разработчиков проекта Saga DeFi Platform.

Quick Start

Prerequisites

Required Software:

# Go 1.21+ для backend
go version

# Node.js 18+ для frontend
node --version
npm --version

# Docker для контейнеризации
docker --version

# PostgreSQL 15+ для БД
psql --version

# Git для version control
git --version

Optional Tools:

# Foundry для blockchain
forge --version
anvil --version

# Make для команд
make --version

Initial Setup

# 1. Clone repository
git clone git@github.com:aiseeq/saga.git
cd saga

# 2. Копировать .env template
cp .env.example .env

# 3. Настроить переменные окружения
# Отредактировать .env файл с корректными значениями

# 4. Установить зависимости
make install

# 5. Запустить систему
make restart

Project Structure

saga/
├── backend/           # Go backend (REST API)
│   ├── cmd/          # Entry points
│   ├── shared/       # Shared logic
│   ├── auth/         # Authentication
│   ├── storage/      # Database layer
│   └── tests/        # Backend tests
├── frontend/         # Next.js applications
│   ├── user-app/     # User interface
│   ├── admin-app/    # Admin panel
│   ├── shared/       # Shared components
│   └── e2e/          # E2E tests
├── blockchain/       # Smart contracts
│   └── local-node/   # Foundry contracts
├── docs/             # Documentation
├── tools/            # Development tools
└── scripts/          # Automation scripts

Development Workflow

1. Backend Development

# Запуск backend тестов
make unit           # Unit tests
make core           # Integration tests
make smoke          # Quick smoke tests

# Работа с БД
psql -U aisee -h 127.0.0.1 -d saga

# Создание миграции
./bin/migrate create -name "new_migration"

# Применение миграций
./bin/migrate up

2. Frontend Development

# Установка зависимостей
cd frontend/user-app && npm install
cd frontend/admin-app && npm install

# Development servers (в контейнере)
# Frontend served через Go server на port 8080

# Тестирование
make e2e-smoke      # Quick E2E tests
make test-all       # Full test suite

3. Blockchain Development

# VPS blockchain (production)
make -f makefiles/development.mk vps-status

# Deploy контрактов
make -f makefiles/development.mk vps-init

# Тестирование контрактов
cd blockchain/local-node
npm run test

🔑 Key Concepts

UnifiedConfig System

// ВСЕГДА используй UnifiedConfig для настроек
cfg := config.LoadUnifiedConfig()

// Получение конфигурации
port := cfg.GetServerPort()
secret := cfg.GetJWTSecret()
rpcURL := cfg.GetBlockchainRPCURL()

SafeDecimal для финансов

import "github.com/aiseeq/saga/backend/shared/models"

// ВСЕ финансовые операции используют SafeDecimal
amount := models.MustParseSafeDecimal("100.50")
balance := models.NewSafeDecimalFromFloat64(1000.0)

// Операции
sum := amount.Add(balance)
result := amount.Multiply(models.NewSafeDecimalFromInt(2))

Handler → Service → Repository

// Backend архитектура ВСЕГДА следует этому паттерну
// 1. Handler принимает HTTP requests
func (h *UserHandler) GetBalance(w http.ResponseWriter, r *http.Request) {
    // Parse request
    // 2. Call Service для business logic
    balance, err := h.service.GetUserBalance(ctx, userID)
    // 3. Return response
    http_helpers.SendSuccess(w, balance)
}

// Service реализует business logic
func (s *BalanceService) GetUserBalance(ctx context.Context, userID int64) (*Balance, error) {
    // 4. Call Repository для database operations
    return s.repo.GetUserBalance(ctx, userID)
}

// Repository работает с БД
func (r *BalanceRepository) GetUserBalance(ctx context.Context, userID int64) (*Balance, error) {
    // SQL query
}

Testing

Test Types

Unit Tests (Go)

make unit           # ~30 seconds
# Focus: Business logic, isolated components

Integration Tests (Go)

make core           # ~2 minutes
# Focus: API endpoints, database interactions

E2E Tests (Playwright)

make e2e-smoke      # ~30 seconds - critical paths
make test-all       # ~3 minutes - full coverage
# Focus: Full user workflows, UI interactions

Writing Tests

Go Test Example:

func TestUserRegistration(t *testing.T) {
    cfg := config.LoadTestConfig()
    db := setupTestDB(t)
    defer db.Close()

    service := NewUserService(db, cfg)

    user, err := service.RegisterUser(ctx, email, walletAddr)
    require.NoError(t, err)
    assert.Equal(t, email, user.Email)
}

E2E Test Example:

import { test, expect } from '@playwright/test';

test('user registration flow', async ({ page }) => {
    await page.goto('/');
    await page.click('[data-testid="connect-wallet"]');
    await page.fill('[data-testid="email-input"]', 'test@example.com');
    await page.click('[data-testid="register-button"]');

    await expect(page.locator('[data-testid="success-message"]')).toBeVisible();
});

Essential Documentation

Architecture

Development

API Documentation

Troubleshooting

Common Issues

Docker контейнер не запускается:

make status         # Check container status
make restart        # Restart container
docker logs saga    # Check logs

Backend не компилируется:

go mod tidy         # Update dependencies
make build          # Build backend

Тесты падают:

make restart        # Ensure backend running
make smoke          # Run quick tests first

База данных проблемы:

psql -U aisee -h 127.0.0.1 -d saga  # Connect to DB
\dt                                  # List tables
\q                                   # Quit

Learning Path

Week 1: Setup & Basics

  • ✅ Complete initial setup
  • ✅ Run make test-all successfully
  • ✅ Read Architecture Overview
  • ✅ Explore codebase structure

Week 2: Backend

  • ✅ Understand Handler → Service → Repository pattern
  • ✅ Learn UnifiedConfig system
  • ✅ Study SafeDecimal usage
  • ✅ Write your first unit test

Week 3: Frontend

  • ✅ Explore Next.js apps structure
  • ✅ Understand shared components
  • ✅ Learn Web3 integration
  • ✅ Write your first E2E test

Week 4: Full Stack

  • ✅ Implement a small feature end-to-end
  • ✅ Add tests for your feature
  • ✅ Create documentation
  • ✅ Submit your first PR

🤝 Getting Help

Communication:

  • Telegram: @AiSeeQ для вопросов и обсуждений
  • GitHub Issues: Bug reports, feature requests
  • Code Reviews: Submit PRs for feedback

Resources:

Next Steps

  1. ✅ Complete setup following Quick Start
  2. ✅ Run make test-all to verify everything works
  3. ✅ Pick a "good first issue" from GitHub
  4. ✅ Read relevant documentation
  5. ✅ Implement your first feature
  6. ✅ Submit a PR



📋 Метаданные

Версия: 2.4.82

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

Статус: Published