# 🐳 Docker Deployment Documentation

Complete guide for deploying and testing the H2H betting platform with blockchain integration in Docker.

## 📚 Documentation Files

| File | Purpose | When to Use |
|------|---------|-------------|
| **DOCKER_QUICK_START.md** | Quick reference card | When you need fast commands |
| **DOCKER_TESTING_GUIDE.md** | Comprehensive testing guide | Full deployment walkthrough |
| **DOCKER_EXPECTED_RESULTS.md** | Visual guide of expected output | Verification and troubleshooting |
| **test-docker.sh** | Automated test script | One-command deployment test |

## 🚀 Quick Start (30 seconds)

**Prerequisites**: Docker Desktop must be running (green icon in menu bar)

```bash
# Run automated deployment test
./test-docker.sh
```

This will:
- ✅ Build Docker images with blockchain integration
- ✅ Start backend and frontend containers
- ✅ Seed database with test users
- ✅ Verify all services are working
- ✅ Check blockchain files are present

**Expected time**: 3-5 minutes (first time), ~30 seconds (subsequent runs)

## 📖 Step-by-Step Guide

### 1. Ensure Docker is Running

Check Docker Desktop is started:
```bash
docker --version
# Should show: Docker version 28.x.x
```

### 2. Run Automated Tests

```bash
chmod +x test-docker.sh
./test-docker.sh
```

### 3. Access Application

**Frontend**: http://localhost:5173
```
Login with:
Email: alice@example.com
Password: password123
```

**Backend API**: http://localhost:8000/docs

### 4. Verify Blockchain Integration

In the browser, check for:
- ⛓️ Blockchain badges on bet cards
- "Connect Wallet" button in header
- Gas estimate panels in bet creation/acceptance
- "On-Chain Escrow" section in wallet (when connected)

### 5. Stop Services

```bash
docker compose down
```

## 🎯 What Gets Deployed

### Backend Container
- FastAPI server on port 8000
- SQLite database with blockchain fields:
  - `bets.blockchain_bet_id`
  - `bets.blockchain_tx_hash`
  - `bets.blockchain_status`
  - `wallets.blockchain_escrow`
- Blockchain services:
  - `blockchain_service.py` - Web3 integration
  - `blockchain_indexer.py` - Event syncing
  - `oracle_node.py` - API data fetching
  - `oracle_aggregator.py` - Consensus mechanism

### Frontend Container
- Vite dev server on port 5173
- React application with blockchain UI:
  - Web3 wallet connection hooks
  - Gas estimate components
  - Transaction progress modals
  - Blockchain status badges
- Modified components:
  - BetCard with blockchain badges
  - CreateBetModal with gas estimates
  - BetDetails with transaction flow
  - WalletBalance with on-chain section
  - Header with wallet connect button

## 🔍 Verification Checklist

Run through this checklist after deployment:

### Backend ✅
- [ ] Container is running: `docker compose ps`
- [ ] API docs accessible: http://localhost:8000/docs
- [ ] Login works: Test with curl or Swagger UI
- [ ] Blockchain files present: `docker compose exec backend ls app/blockchain/`

### Frontend ✅
- [ ] Container is running: `docker compose ps`
- [ ] App loads: http://localhost:5173
- [ ] Login page renders
- [ ] Can authenticate with test credentials
- [ ] Blockchain hooks present: `docker compose exec frontend ls src/blockchain/`

### UI Features ✅
- [ ] Blockchain badges visible on bet cards
- [ ] "Connect Wallet" button in header
- [ ] Gas estimate in Create Bet modal
- [ ] Gas estimate panel on Bet Details
- [ ] "On-Chain Escrow" section in Wallet
- [ ] Transaction modals configured

### Integration ✅
- [ ] No import errors in logs
- [ ] TypeScript compiles without errors
- [ ] All API endpoints responding
- [ ] WebSocket connections work
- [ ] Database has blockchain fields

## 🛠️ Common Commands

```bash
# Start services
docker compose up -d

# View logs
docker compose logs -f
docker compose logs -f backend
docker compose logs -f frontend

# Stop services
docker compose down

# Rebuild everything
docker compose build --no-cache
docker compose up -d

# Reset database
docker compose down -v
docker compose up -d
docker compose exec backend python seed_data.py

# Shell access
docker compose exec backend bash
docker compose exec frontend sh

# Check resource usage
docker stats

# Remove everything (nuclear option)
docker compose down -v
docker system prune -af
```

## 🐛 Troubleshooting

### Services Won't Start

```bash
# Check Docker daemon
docker info

# Check port availability
lsof -ti:8000
lsof -ti:5173

# View detailed logs
docker compose logs
```

### Import Errors

```bash
# Rebuild backend
docker compose build --no-cache backend
docker compose up -d backend

# Check Python imports
docker compose exec backend python -c "from app.blockchain.services.blockchain_service import BlockchainService; print('OK')"
```

### Frontend Build Errors

```bash
# Rebuild frontend
docker compose build --no-cache frontend
docker compose up -d frontend

# Check TypeScript
docker compose exec frontend npm run type-check
```

### Database Issues

```bash
# Reset and reseed
docker compose down -v
docker compose up -d
sleep 10
docker compose exec backend python seed_data.py
```

## 📊 Performance Benchmarks

Expected performance in Docker:

| Metric | Expected Value |
|--------|----------------|
| Build time (first) | 3-5 minutes |
| Build time (cached) | 10-30 seconds |
| Startup time | 10-30 seconds |
| Backend memory | < 200MB |
| Frontend memory | < 500MB |
| API response time | < 100ms |
| Page load time | < 2s |

## 🔐 Security Notes

**Development Environment Only**

Current configuration is for development:
- SQLite database (use PostgreSQL in production)
- Hot reload enabled (disable in production)
- Debug logging (reduce in production)
- Default JWT secret (change in production)
- Ports exposed (use reverse proxy in production)

**For Production**:
1. Use PostgreSQL instead of SQLite
2. Set secure JWT_SECRET
3. Disable debug mode
4. Use production build (not dev server)
5. Add reverse proxy (nginx)
6. Enable HTTPS
7. Set up proper logging
8. Configure monitoring

## 📝 Test Scenarios

### Scenario 1: Fresh Deployment

```bash
docker compose down -v
./test-docker.sh
# Expected: All checks pass, can login and see UI
```

### Scenario 2: Code Changes

```bash
# Make code changes in your editor
docker compose restart backend  # If backend changes
docker compose restart frontend # If frontend changes
# Expected: Changes reflected due to volume mounts
```

### Scenario 3: Database Reset

```bash
docker compose down -v
docker compose up -d
docker compose exec backend python seed_data.py
# Expected: Fresh database with test users
```

### Scenario 4: Full Rebuild

```bash
docker compose down -v
docker compose build --no-cache
docker compose up -d
# Expected: Clean build with all latest changes
```

## 🎓 Learning Resources

### Understanding the Architecture

```
┌─────────────────────────────────────────┐
│  Browser (http://localhost:5173)       │
└───────────────┬─────────────────────────┘
                │
                │ HTTP/WebSocket
                │
┌───────────────▼─────────────────────────┐
│  Frontend Container (Vite/React)        │
│  - Blockchain UI components             │
│  - Web3 wallet hooks                    │
│  - Gas estimate displays                │
└───────────────┬─────────────────────────┘
                │
                │ API Calls
                │
┌───────────────▼─────────────────────────┐
│  Backend Container (FastAPI)            │
│  - Blockchain services                  │
│  - Oracle system                        │
│  - Web3 integration                     │
│  - SQLite with blockchain fields        │
└─────────────────────────────────────────┘
```

### Blockchain Integration Flow

```
1. User clicks "Create Bet"
   → Frontend shows gas estimate

2. User confirms
   → useBlockchainBet hook prepares transaction

3. MetaMask prompts (would in production)
   → User signs transaction

4. Transaction sent to blockchain (would in production)
   → TransactionModal shows progress

5. Backend indexes event
   → blockchain_indexer.py syncs to database

6. UI updates
   → Blockchain badge appears on bet card
```

## 📦 What's Included

### Smart Contract Documentation
- BetEscrow contract design (pseudocode)
- BetOracle contract design (pseudocode)
- Architecture diagrams
- Security model

### Backend Services
- Web3 provider integration
- Event indexing system
- Oracle node implementation
- Consensus aggregator
- Network configuration

### Frontend Integration
- MetaMask connection hooks
- Transaction management
- Gas estimation
- Blockchain status badges
- Transaction progress modals

### UI Enhancements
- Bet cards with blockchain badges
- Create modal with gas estimates
- Detail page with transaction flow
- Wallet with on-chain section
- Header with wallet button

## 🎉 Success Criteria

Your Docker deployment is successful when:

✅ `./test-docker.sh` completes with all checks passing
✅ Both containers show "Up" status
✅ Can login at http://localhost:5173
✅ API docs accessible at http://localhost:8000/docs
✅ Blockchain badges visible in UI
✅ Connect Wallet button in header
✅ Gas estimates show in modals
✅ No critical errors in logs
✅ All blockchain files present in containers

## 🚢 Next Steps

After successful Docker deployment:

1. **Test Full Workflow**: Create, accept, and settle bets
2. **Explore API**: Use Swagger UI at http://localhost:8000/docs
3. **Check Logs**: Monitor application behavior
4. **Verify UI**: Test all blockchain integration points
5. **Review Code**: Examine blockchain service implementations
6. **Plan Production**: Review BLOCKCHAIN_IMPLEMENTATION.md for deployment

## 📞 Support

If you encounter issues:

1. Check `DOCKER_EXPECTED_RESULTS.md` for expected output
2. Review `DOCKER_TESTING_GUIDE.md` for detailed steps
3. Run `./test-docker.sh` for automated diagnostics
4. Check logs: `docker compose logs -f`
5. Try full rebuild: `docker compose down -v && docker compose build --no-cache`

---

**Ready to deploy?** Run `./test-docker.sh` now! 🚀
