OverviewMoney Flow

Money Flow Architecture

Overview

Wafra’s money flow architecture enables seamless fiat-to-fiat yield generation through a sophisticated three-phase system: deposit, yield generation, and withdrawal. This architecture abstracts away the complexity of DeFi while maximizing returns for users.

Current Implementation

Fiat Onramp Process

  • Step 1: USD via bank transfer, card, or wire

  • Step 2: DTR or Onramp provider handles conversion

  • Step 3: Unified compliance system across providers

  • Step 4: Payment processor converts fiat to USDC

  • Step 5: USDC received in user’s Gnosis Safe

  • Step 6: Scaled tokens minted based on current exchange rate

  • Step 7: USDC distributed across active yield strategies

Payment Processing

Wafra integrates multiple payment providers for optimal rates and global coverage. For detailed provider information and implementation, see Payment Providers.

Smart Contract Integration

Wafra operates on Base L2 with 6 active yield strategies and upgradeable contract architecture. For complete contract addresses and technical details, see Smart Contracts Overview.

WST Token Mechanics

Scaled Balance System:

// Actual balance calculation
function balanceOf(address account) returns (uint256) {
    return (_scaledBalances[account] * liquidityIndex) / PRECISION;
}
 
// Exchange rate calculation
function getExchangeRate() returns (uint256) {
    return (liquidityIndex * 1e6) / PRECISION;
}

Key Features:

  • Automatic Yield Accrual: Balance increases without transactions
  • Compound Interest: Interest compounds continuously
  • Liquidity Index: Tracks total yield generation (starts at 1e27)

Active Yield Strategies

Current Strategy Portfolio

StrategyImplementationRisk LevelExpected APYCurrent Status
Aave LendingLiveLow3-5%✅ Active
Morpho BlueLiveLow-Medium4-7%✅ Active
Pendle TradingLiveMedium6-12%✅ Active
Anzen RWADevelopmentLow-Medium4-8%�� Testing

Strategy Allocation Logic

Current Implementation:

  • Risk-Weighted Distribution: Lower allocation to higher-risk strategies
  • Liquidity Management: Maintains reserves for withdrawals
  • Dynamic Rebalancing: Based on performance and market conditions
  • Capacity Limits: Maximum allocation per strategy

Allocation Process:

// Simplified allocation logic
for (uint i = 0; i < strategies.length; i++) {
    uint256 allocation = (totalAmount * strategyWeights[i]) / 10000;
    strategies[i].deposit(allocation);
}

Real-Time Monitoring System

Blockchain Data Sync

Current Implementation:

  • Block Processing: Monitors Base network with 5-block safety margin
  • Event Listeners: USDC transfers, fund operations, strategy actions
  • Balance Tracking: Real-time wallet balance updates
  • Gas Monitoring: Tracks transaction costs in ETH and USD

Transaction Listener Architecture:

// Simplified event handler structure
const handlers = [
  {
    signature: "Transfer(address,address,uint256)",
    contract: USDC_CONTRACT,
    handler: handleUSDCTransfer,
  },
  {
    signature: "Deposit(address,uint256)",
    contract: FUND_CONTRACT,
    handler: handleDeposit,
  },
];

Real-Time Notifications

Socket.IO Events:

  • Balance updates when deposits arrive
  • Transaction status changes
  • Yield accrual notifications
  • Strategy performance updates

Yield Generation Process

Daily Yield Accrual

Current Process:

  • Step 1: Each strategy collects generated yield
  • Step 2: Total yield calculated across all strategies
  • Step 3: Liquidity index updated based on yield
  • Step 4: User balances automatically increase
  • Step 5: Real-time balance updates sent to users

Exchange Rate Calculation

Current Formula:

// Daily yield accrual
newLiquidityIndex = oldLiquidityIndex * (1 + dailyYieldRate);
 
// User balance
userBalance = (scaledBalance * liquidityIndex) / PRECISION;

Withdrawal Flow

Current Withdrawal Process

Implementation Steps:

  • Step 1: User initiates via mobile app
  • Step 2: WST tokens burned to release USDC
  • Step 3: USDC withdrawn from yield strategies
  • Step 4: USDC sent to payment provider
  • Step 5: Provider converts USDC to USD
  • Step 6: USD transferred to user’s bank account

Liquidity Management

Current Strategy:

  • Reserve Pool: Maintains USDC reserves for instant withdrawals
  • Sequential Withdrawal: Withdraws from strategies in order of liquidity
  • Slippage Protection: Prevents excessive slippage during large withdrawals

Fee Structure (Current)

Management Fees

Current Implementation:

  • Weekly Fee Rate: 2% APY charged to fund
  • Fee Collection: Automated weekly collection
  • Treasury Allocation: 75% to treasury, 25% to referral program

Revenue Distribution

Performance Metrics

Current Tracking

Database Storage:

  • Daily fund metrics (APY, share price, total value)
  • Strategy performance by vault
  • Gas cost analysis
  • User balance history

Real-Time Calculations:

  • Live APY based on recent performance
  • Strategy allocation percentages
  • Total value locked (TVL)
  • Exchange rate movements

Analytics Dashboard

Current Metrics:

  • Fund performance over time
  • Strategy contribution to yield
  • User growth and retention
  • Transaction volume and costs

Data Flow Architecture

System Architecture Overview

Wafra’s data flow architecture combines modern React Native patterns with robust backend services, real-time communication, and blockchain integration. The system employs a multi-layered approach designed around secure DeFi yield farming with comprehensive user experience optimization.

API Communication Patterns

TRPC-Based Type-Safe Communication

Core Architecture Features:

  • End-to-end TypeScript type safety from database schemas to React Native components
  • JWT-based authentication with session management and user context injection
  • HTTP batch processing for efficient request optimization (2000 char URL limit)
  • Standardized error handling with Zod validation

Key Router Endpoints:

RouterPurposeLines of CodeKey Features
balances.tsReal-time balance queries~200Async balance updates, yield calculations
payment.tsPayment orchestration1,286Multi-provider integration, quote optimization
transactions.tsBlockchain operations~400Transaction building, passkey integration
wallet.tsSafe wallet management~300Multi-signature operations, device management
auth.tsAuthentication flows~250Traditional + WebAuthn passkey authentication
kyc.tsCompliance management~200Document handling, status tracking

Client-Side Data Management

React Query Integration:

  • 5-minute default stale time for efficient caching
  • Smart retry logic with authentication-aware failure handling
  • Optimistic updates for immediate UI responsiveness
  • Background data synchronization

State Management Architecture

Hook-Based State Management

The system uses sophisticated custom hooks for state orchestration:

// Core state management hooks
useSession()        // Global auth state with AsyncStorage persistence
useBalances()       // Real-time balance tracking with auto-refresh
useTransactions()   // Complex transaction building with passkey flows
useAuth()          // Authentication flows including passkey login

Local Storage Patterns

AsyncStorage Implementation:

  • Persistent authentication tokens
  • User preferences and settings
  • Cached wallet addresses
  • Theme and UI state

React Context Providers:

  • TRPC client configuration
  • Global session management
  • Theme and styling context

Real-Time Data Synchronization

Socket.IO Event Architecture

User-Specific Channels:

  • Individual user rooms (user-${userId}) for targeted updates
  • Secure event broadcasting with user isolation
  • Connection management with authentication verification

Event Types:

// Real-time event specifications
interface SocketEvents {
  'balance-update': BalanceUpdatePayload;
  'transaction-update': TransactionStatusPayload;
  'payment-success': PaymentCompletionPayload;
  'payment-failed': PaymentErrorPayload;
  'device-approval-request': PasskeyApprovalPayload;
  'kyc-status-update': KYCStatusPayload;
}

Real-Time Update Flow

Data Persistence Patterns

Database Architecture (PostgreSQL + Prisma)

Core Data Models:

ModelPurposeKey Relationships
UserCentral user entity→ AccountBalance, Order, Passkey
PasskeyWebAuthn credentials→ User, Device management
AccountBalanceReal-time balances→ User, Yield calculations
OrderPayment transactions→ User, OnrampTransaction
TaskAsync operations→ User, Retry management
EventUser notifications→ User, Status tracking

Caching Strategy

Multi-Layer Caching:

  • L1 Cache: React Query client-side API response caching
  • L2 Cache: Server-side wallet address caching for blockchain operations
  • L3 Cache: Computed fund metrics and yield calculations

Async Task Management System

Task Processing Architecture

Task Types and Processing:

enum TaskType {
  SAFE_DEPLOYMENT = 'safe_deployment',      // Wallet creation
  PASSKEY_ADDITION = 'passkey_addition',    // WebAuthn setup
  ACCOUNT_CREATION = 'account_creation'     // Complete onboarding
}

Processing Features:

  • Exponential backoff retry logic with intelligent error classification
  • Task dependency management with prerequisite validation
  • Comprehensive lifecycle tracking with status updates
  • Event-driven completion notifications

Task Flow Example

Blockchain Integration Patterns

Event Processing System

Block Processing Strategy:

  • Incremental block processing with 5-block safety margin
  • Batch log retrieval for efficiency (5 blocks per batch)
  • Event-driven handlers for specific contract interactions
  • Comprehensive error recovery with retry mechanisms

Smart Contract Integration:

// Event handler architecture
interface EventHandler {
  signature: string;           // Event signature
  contract: string;           // Contract address
  handler: (log: Log) => Promise<void>;
}
 
// Example handlers
const handlers: EventHandler[] = [
  {
    signature: "Transfer(address,address,uint256)",
    contract: USDC_CONTRACT,
    handler: handleUSDCTransfer
  },
  {
    signature: "Deposit(address,uint256)", 
    contract: FUND_CONTRACT,
    handler: handleDeposit
  }
];

Payment Provider Integration

Service Architecture Pattern

Abstract Base Service:

abstract class BasePaymentService {
  abstract getQuote(params: QuoteParams): Promise<Quote | null>;
  abstract createOrder(user: User, params: TransactionParams): Promise<TransactionResult>;
  abstract handleWebhook(payload: any, headers?: IncomingHttpHeaders): Promise<any>;
}

Provider Implementations:

  • Onramp Service: Primary provider with comprehensive KYC flows
  • DTR Service: Alternative provider with different geographic coverage
  • Composite Service: Multi-provider orchestration with best quote selection

Data Flow Patterns

Synchronous Request Flows:

  1. Authentication: Credentials → JWT → Session → Context
  2. Balance Queries: Client → TRPC → Blockchain → Database → Response
  3. Payment Quotes: Client → Payment Service → Provider API → Response

Asynchronous Event Flows:

  1. Blockchain Events: Block Listener → Event Handlers → Database → Socket Updates
  2. Payment Processing: Webhook → Provider → Database → Socket Notification
  3. Wallet Operations: Task Queue → Safe Deployment → Passkey Addition → Completion Event

Performance and Scalability Features

System Optimizations

Request Optimization:

  • TRPC request batching with URL length management
  • React Query stale-while-revalidate caching strategy
  • Background data synchronization without UI blocking

Database Optimization:

  • Prisma-generated type-safe queries
  • Indexed lookups for user and balance queries
  • Connection pooling for concurrent request handling

Real-Time Optimization:

  • User-specific Socket.IO rooms for targeted updates
  • Event batching for high-frequency updates
  • Connection state management with automatic reconnection

This comprehensive data flow architecture provides a robust, scalable foundation for fiat-to-fiat yield generation while maintaining transparency, security, and optimal user experience.