Saltar al contenido principal

Flujo Completo: Del Registro a la Primera Transacción

Este documento explica el viaje completo de un usuario desde que se registra hasta que envía su primera transacción en SwapBits.


Vista General del Journey


Fase 1: Registro de Usuario

Flujo Técnico Completo

Datos Guardados en MongoDB

{
_id: ObjectId("..."),
email: "user@example.com",
username: "johndoe",
password: "$2b$10$...", // Hash bcrypt
firstName: "John",
lastName: "Doe",
emailVerified: true,
phoneVerified: false,
twoFactorEnabled: false,
kycStatus: "not_started",
status: "active",
createdAt: ISODate("2025-10-20T10:00:00Z"),
updatedAt: ISODate("2025-10-20T10:05:00Z")
}

Fase 2: Login y Autenticación

Login Básico (Email/Password)

JWT Token Generado

// Access Token (válido 15 minutos)
{
userId: "user_123",
email: "user@example.com",
role: "USER",
iat: 1697808000, // Issued at
exp: 1697808900 // Expires (15 min después)
}

// Refresh Token (válido 7 días)
{
userId: "user_123",
type: "refresh",
iat: 1697808000,
exp: 1698412800 // 7 días después
}

Sesión en Redis

// Key: session:user_123:abc123def
{
userId: "user_123",
deviceId: "fingerprint_hash",
ip: "192.168.1.1",
userAgent: "Mozilla/5.0...",
createdAt: "2025-10-20T10:00:00Z",
expiresAt: "2025-10-27T10:00:00Z"
}
// TTL: 7 días

Fase 3: Verificación KYC (Opcional)

¿Cuándo se requiere KYC?

AcciónRequiere KYCLímite sin KYC
Crear wallet❌ No-
Recibir fondos❌ No-
Enviar < $100❌ No$100/día
Enviar > $100✅ Sí-
Trading✅ Sí-
Retiro fiat✅ Sí-

Flujo de KYC


Fase 4: Crear Wallet

Flujo de Creación

Wallet Guardada en MongoDB

{
_id: ObjectId("..."),
userId: ObjectId("user_123"),
address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
coin: "ETH",
type: "EVM",
privateKeyHash: "abc123...", // SHA-256 hash
balance: 0,
createdAt: ISODate("2025-10-20T10:30:00Z")
}

Fase 5: Recibir Fondos (Primera Transacción Entrante)

Flujo de Detección

Transacción Guardada

{
_id: ObjectId("..."),
walletId: ObjectId("wallet_123"),
userId: ObjectId("user_123"),
txHash: "0x123abc...",
type: "received",
from: "0xabc...",
to: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
amount: 0.5,
coin: "ETH",
network: "ethereum",
status: "confirmed",
confirmations: 12,
blockNumber: 18234567,
usdValue: 750.00,
timestamp: ISODate("2025-10-20T11:00:00Z")
}

Fase 6: Enviar Primera Transacción

Flujo de Envío Completo

Validaciones Antes de Enviar

// 1. Balance suficiente
if (wallet.balance < amount + estimatedFee) {
throw new BadRequestException('Insufficient balance');
}

// 2. PIN correcto
const pinValid = await this.pinService.verify(userId, pin);
if (!pinValid) {
throw new UnauthorizedException('Invalid PIN');
}

// 3. Rate limiting
const limit = await this.rateLimit.check(`send:${userId}`, 5, 3600000); // 5 tx/hora
if (limit.exceeded) {
throw new TooManyRequestsException('Rate limit exceeded');
}

// 4. Address válida
if (!web3.utils.isAddress(to)) {
throw new BadRequestException('Invalid address');
}

// 5. Monto dentro de límites
if (amount < MIN_AMOUNT || amount > MAX_AMOUNT) {
throw new BadRequestException('Amount out of bounds');
}

// 6. KYC para montos grandes
if (usdValue > 1000 && !user.kycApproved) {
throw new ForbiddenException('KYC required for large transactions');
}

Resumen del Journey Completo


Tiempos Aproximados

FaseTiempo Estimado
Registro2 minutos
Verificación Email1-5 minutos
Login5 segundos
KYC (opcional)3-10 minutos
Crear Wallet3 segundos
Recibir Fondos15 segundos - 10 minutos (según blockchain)
Confirmar Recepción3-15 minutos (según blockchain)
Enviar Transacción10 segundos
Confirmar Envío3-15 minutos (según blockchain)

Tiempo total mínimo (sin KYC): ~20 minutos
Tiempo total con KYC: ~30-40 minutos


Estados de Usuario a lo Largo del Journey

// Estado 1: Recién registrado
{
status: "active",
emailVerified: false,
kycStatus: "not_started",
wallets: [],
transactions: []
}

// Estado 2: Email verificado, sin KYC
{
status: "active",
emailVerified: true,
kycStatus: "not_started",
wallets: [],
transactions: []
}

// Estado 3: Con wallet, esperando fondos
{
status: "active",
emailVerified: true,
kycStatus: "not_started",
wallets: [{ coin: "ETH", balance: 0 }],
transactions: []
}

// Estado 4: Con fondos, listo para operar
{
status: "active",
emailVerified: true,
kycStatus: "not_started", // o "approved"
wallets: [{ coin: "ETH", balance: 0.5 }],
transactions: [
{ type: "received", amount: 0.5, status: "confirmed" }
]
}

// Estado 5: Usuario activo
{
status: "active",
emailVerified: true,
kycStatus: "approved",
wallets: [{ coin: "ETH", balance: 0.4 }],
transactions: [
{ type: "received", amount: 0.5, status: "confirmed" },
{ type: "sent", amount: 0.1, status: "confirmed" }
]
}

Para Desarrolladores

Este flujo es el más común y el que debes entender perfectamente. La mayoría de bugs reportados por usuarios están en algún punto de este journey.

Debugging por fase:

  1. Registro no funciona: Revisar Auth Service logs
  2. Email no llega: Revisar Email Service y spam
  3. No puede login: Verificar JWT en Redis
  4. Wallet no se crea: Revisar Lambda logs en CloudWatch
  5. Fondos no aparecen: Verificar Monitor service
  6. Transacción no se envía: Revisar Wallet Service + Lambda

Testing end-to-end: Ejecuta este flujo completo en staging antes de cada deploy a producción.