# Tiered Architecture Setup Guide

Complete setup and integration guide for SolaceScan tiered architecture.

## Quick Start

```bash
# 1. Run the setup script
cd explorer-monorepo
bash scripts/setup-tiered-architecture.sh

# 2. Set required environment variables
export JWT_SECRET="your-strong-random-secret-here"
export RPC_URL="http://192.168.11.250:8545"
export DB_HOST="localhost"
export DB_USER="explorer"
export DB_PASSWORD="changeme"
export DB_NAME="explorer"

# 3. Start the API server
cd backend
./bin/api-server
```

## Environment Variables

### Required
- `DB_HOST` - PostgreSQL host (default: localhost)
- `DB_USER` - Database user (default: explorer; use `blockscout` for the shared Blockscout DB mode)
- `DB_PASSWORD` - Database password (default: changeme)
- `DB_NAME` - Database name (default: explorer; use `blockscout` for the shared Blockscout DB mode)

### Recommended (Production)
- `JWT_SECRET` - Strong random secret for JWT signing (required for production)
- `RPC_URL` - RPC endpoint for Track 1 gateway (default: http://localhost:8545)
- `CHAIN_ID` - Chain ID (default: 138)
- `PORT` - API server port (default: 8080)

## Database Migration

Run the migration helper:

```bash
bash scripts/run-migration-0010.sh
```

The helper auto-detects the database layout:

- **Standalone explorer DB**: creates the full Track 2-4 schema
- **Shared Blockscout DB**: creates only `operator_events`, `operator_ip_whitelist`, `operator_roles`, and `wallet_nonces`

Do **not** apply `backend/database/migrations/0010_track_schema.up.sql` directly to the shared Blockscout DB.

## User Management

### Approve a User for Track 2-4

```bash
# Approve user for Track 2
bash scripts/approve-user.sh 0x1234...5678 2

# Approve user for Track 3
bash scripts/approve-user.sh 0x1234...5678 3

# Approve user for Track 4 (operator)
bash scripts/approve-user.sh 0x1234...5678 4 0xAdminAddress
```

### Add IP to Operator Whitelist (Track 4)

```bash
bash scripts/add-operator-ip.sh 0x1234...5678 192.168.1.100 "Office network"
```

## API Endpoints

### Track 1 (Public - No Auth)
- `GET /api/v1/track1/blocks/latest` - Latest blocks
- `GET /api/v1/track1/txs/latest` - Latest transactions
- `GET /api/v1/track1/block/:number` - Block by number
- `GET /api/v1/track1/tx/:hash` - Transaction by hash
- `GET /api/v1/track1/address/:addr/balance` - Address balance
- `GET /api/v1/track1/bridge/status` - Bridge status

### Track 2 (Authenticated - Track 2+)
- `GET /api/v1/track2/address/:addr/txs` - Address transaction history
- `GET /api/v1/track2/address/:addr/tokens` - Address token balances
- `GET /api/v1/track2/token/:contract` - Token information
- `GET /api/v1/track2/search?q=` - Enhanced search
- `GET /api/v1/track2/address/:addr/internal-txs` - Internal transactions

### Track 3 (Authenticated - Track 3+)
- `GET /api/v1/track3/analytics/flows` - Flow tracking
- `GET /api/v1/track3/analytics/bridge` - Bridge analytics
- `GET /api/v1/track3/analytics/token-distribution/:contract` - Token distribution
- `GET /api/v1/track3/analytics/address-risk/:addr` - Address risk analysis

### Track 4 (Authenticated - Track 4 + IP Whitelist)
- `GET /api/v1/track4/operator/bridge/events` - Bridge operator events
- `GET /api/v1/track4/operator/validators` - Validator status
- `GET /api/v1/track4/operator/contracts` - Contract registry
- `GET /api/v1/track4/operator/protocol-state` - Protocol state

### Authentication
- `POST /api/v1/auth/nonce` - Request nonce for wallet auth
- `POST /api/v1/auth/wallet` - Authenticate with wallet signature

### Feature Flags
- `GET /api/v1/features` - Get available features for current user

## Frontend Integration

The frontend automatically:
1. Loads feature flags on page load
2. Shows/hides UI elements based on track level
3. Provides wallet connect button for authentication
4. Stores auth token in localStorage

### Testing Authentication

1. Open browser console
2. Connect wallet using the "Connect Wallet" button
3. Sign the authentication message
4. Check `localStorage.getItem('authToken')` to verify token storage
5. Check feature flags: `fetch('/api/v1/features').then(r => r.json())`

## Indexer Setup

To populate Track 2 data, start the indexers:

```bash
cd backend/indexer
go run main.go
```

The indexers will:
- Index blocks and transactions
- Extract ERC-20 token transfers
- Update address statistics
- Build analytics data

## Production Considerations

1. **JWT Secret**: Must be set to a strong random value
2. **Redis**: Replace in-memory cache/rate limiter with Redis
3. **HTTPS**: Use HTTPS in production
4. **Rate Limiting**: Configure appropriate rate limits per track
5. **IP Whitelist**: Strictly enforce for Track 4 operators
6. **Audit Logging**: Monitor `operator_events` table

## Troubleshooting

### Migration Fails
- Check database connection: `psql -h $DB_HOST -U $DB_USER -d $DB_NAME -c "SELECT 1"`
- Verify user has CREATE TABLE permissions
- If you are using the shared Blockscout DB, keep `DB_USER` and `DB_NAME` aligned to `blockscout`

### Authentication Fails
- Check JWT_SECRET is set
- Verify wallet_nonces table exists
- Check database connection in auth handlers
- If the wallet popup shows `Nonce: undefined`, the nonce request failed before signing. Run `bash scripts/run-migration-0010.sh`, restart the backend, and retry.

### Track Routes Not Working
- Verify user is approved: Check `operator_roles` table
- Check track level in JWT token
- Verify middleware is applied correctly

### Frontend Feature Gating Not Working
- Check browser console for errors
- Verify `/api/v1/features` endpoint returns correct track
- Check localStorage for authToken

## Next Steps

1. ✅ Run database migration
2. ✅ Set environment variables
3. ✅ Start API server
4. ✅ Approve test users
5. ✅ Start indexers
6. ✅ Test authentication flow
7. ✅ Verify feature gating

For detailed API documentation, see: `docs/api/track-api-contracts.md`
