Technology Stack
Overview
Wafra leverages a modern, scalable technology stack that combines battle-tested infrastructure with cutting-edge blockchain technology. The platform is built using a monorepo architecture that ensures code consistency, shared libraries, and coordinated deployments across all components.
Architecture Overview
The Wafra platform consists of several interconnected layers that work together to provide a seamless user experience:
Frontend Applications Layer: React Native mobile application for iOS and Android, and a Next.js landing page for web presence.
API & Business Logic Layer: Fastify HTTP server providing high-performance API endpoints, tRPC API layer for type-safe communication, and comprehensive business services handling core functionality.
Blockchain Infrastructure Layer: Solidity smart contracts deployed on Base Network Layer 2, with Viem and Wagmi providing client-side blockchain interaction capabilities.
Data & Storage Layer: PostgreSQL database for persistent data storage, Prisma ORM for database management, and Redis cache for performance optimization.
External Integrations Layer: Payment provider integrations, KYC service connections, and price feed services for real-time market data.
Frontend Technologies
Mobile Application (React Native/Expo)
Wafra’s mobile application is built using React Native with Expo, providing a cross-platform solution that delivers native performance while maintaining development efficiency.
Framework and Runtime: The application uses React Native version 51.x with Expo, enabling cross-platform iOS and Android development from a single codebase. This approach provides native performance through JavaScript execution while offering benefits like hot reloading for rapid development cycles and access to a rich ecosystem of libraries and tools.
State Management Strategy: The primary state management solution is React Query (TanStack Query) for server state management, which provides intelligent caching, background refetching, and optimistic updates. Local state is managed through React Hooks including useState and useReducer, while global application state like authentication is handled through React Context.
Networking and Communication: The mobile client uses tRPC React Query Client for type-safe API communication with the backend. Transport occurs over HTTP with WebSocket fallback for real-time features. The system implements intelligent query caching and invalidation to minimize network requests while ensuring data freshness.
User Interface and Styling: The application uses Tailwind CSS with NativeWind for styling, providing utility-first CSS classes that work across both web and native platforms. Custom design system components ensure consistent user experience. Navigation is handled by Expo Router with file-based routing for intuitive project organization.
Authentication Integration: The mobile application implements WebAuthn for passkey authentication, utilizing device biometrics for secure user verification. The implementation leverages platform-specific security features while providing a consistent API across iOS and Android devices.
Landing Page (Next.js)
The Wafra landing page is built with Next.js 14, providing optimal performance and SEO capabilities for web presence.
Framework Capabilities: Next.js 14 with App Router provides server-side rendering for improved performance and SEO. File-based routing simplifies navigation structure while Server Components optimize performance by reducing client-side JavaScript. Built-in image optimization and SEO features ensure fast loading times and search engine visibility.
Styling and Components: Tailwind CSS provides utility-first styling for rapid development and consistent design. Headless UI components offer accessible, unstyled components that integrate seamlessly with custom designs. The responsive design follows mobile-first principles to ensure optimal experience across all device sizes.
Performance Optimization: Webpack bundling with optimization ensures minimal bundle sizes and fast loading times. Static generation is used where possible to pre-render pages at build time. Web Vitals monitoring provides insights into real-world performance metrics.
Backend Infrastructure
API Server (Node.js + Fastify)
The Wafra backend is built on Node.js with Fastify, providing high-performance API services with modern JavaScript features.
Runtime Environment: Node.js version 20+ provides access to the latest ES2023 JavaScript features, native ESM module support, built-in test runner capabilities, and enhanced performance optimizations. This modern runtime ensures the server can handle high throughput while maintaining developer productivity.
Web Framework Benefits: Fastify was chosen for its superior performance, running approximately 2x faster than Express.js in benchmark tests. Built-in schema validation provides automatic request validation, while automatic documentation generation keeps API documentation in sync with implementation. The rich plugin ecosystem enables modular architecture and code reuse.
API Layer Architecture: tRPC provides end-to-end type safety between client and server, eliminating the need for code generation while ensuring compile-time safety. Automatic client generation reduces development overhead, while built-in validation with Zod schemas ensures data integrity. Optimistic updates support enables responsive user interfaces.
Server Configuration and Security: The Fastify server is configured with comprehensive logging using Pino for structured logging and debugging. CORS support enables cross-origin requests with proper security controls. Rate limiting prevents API abuse and DDoS attacks. The tRPC integration provides a clean separation between transport and business logic.
tRPC API Architecture
The API layer is built using tRPC, providing type-safe communication between frontend and backend with comprehensive middleware support.
Router Organization: The tRPC router follows a modular composition pattern with feature-based routing that scales with application complexity. Nested routers enable logical organization of related endpoints while maintaining type safety across the entire API surface.
Procedure Types and Security: The API implements three types of procedures: public procedures for unauthenticated endpoints like health checks, protected procedures requiring JWT authentication for user-specific operations, and sensitive procedures requiring additional passkey verification for high-security operations like fund transfers.
Validation and Type Safety: Zod schema validation ensures all input data meets specified requirements before processing. TypeScript interfaces provide compile-time type checking for all API responses. Runtime type checking prevents malformed data from causing system errors.
Middleware Stack: Comprehensive middleware provides authentication through JWT token validation, rate limiting to prevent abuse, structured logging for all requests, and centralized error handling with appropriate HTTP status codes and error messages.
Database & Storage
PostgreSQL with Prisma ORM
Wafra uses PostgreSQL as its primary database, managed through Prisma ORM for type-safe database operations.
Database Features and Benefits: PostgreSQL version 16 provides ACID compliance essential for financial data integrity. JSON and JSONB support enables flexible schema design where needed. Advanced indexing capabilities ensure optimal query performance. Built-in replication and backup features provide data reliability and disaster recovery capabilities.
ORM Capabilities: Prisma 5.x provides type-safe database access with automatic TypeScript generation from the database schema. Automatic migration generation simplifies database schema changes while maintaining data integrity. Query optimization analyzes and optimizes database queries automatically. Database introspection enables schema discovery and validation.
Performance Optimization: Built-in connection pooling manages database connections efficiently under high load. Strategic index placement on frequently queried columns ensures optimal performance. Optimized query patterns minimize database round trips. Slow query detection helps identify and resolve performance bottlenecks.
Schema Design Principles: The database schema follows relational design principles with proper normalization. User data is structured with relationships to passkeys, transactions, balances, and referrals. Strategic indexing on email addresses, wallet addresses, and transaction hashes ensures fast lookups. Timestamp indexing enables efficient historical queries.
Redis for Caching & Sessions
Redis provides high-performance caching and session management for the Wafra platform.
Session Storage Strategy: User sessions are stored as JSON-encoded objects with a 5-day time-to-live. Session invalidation occurs through TTL expiration or manual eviction when users log out or security events occur. Each session contains user identification, device information, and authentication state.
Rate Limiting Implementation: Token bucket algorithm implementation provides sophisticated rate limiting capabilities. Redis sorted sets store rate limiting counters with precise timing information. Sliding window counters enable accurate rate limiting across different time periods and endpoints.
Data Caching Strategy: Exchange rates for ETH/USD are cached with 1-minute TTL to provide real-time pricing while minimizing external API calls. Network gas prices are cached with 30-second TTL for optimal transaction timing. User balances are cached and invalidated immediately upon transaction completion to ensure accuracy.
Cache Service Implementation: The Redis cache service provides methods for session management, rate limiting enforcement, and data caching. Session management includes creation, retrieval, and invalidation capabilities. User session invalidation can target specific sessions or all sessions for a user during security events.
Blockchain Infrastructure
Smart Contract Platform
Wafra’s smart contracts are deployed on Base, an Ethereum Layer 2 solution that provides low-cost, fast transactions while maintaining Ethereum security guarantees.
Network Selection Benefits: Base Network provides extremely low transaction costs averaging around $0.01 per transaction. Fast finality of approximately 2 seconds ensures responsive user experience. Full Ethereum security guarantees through optimistic rollup technology. Complete EVM compatibility ensures seamless integration with existing Ethereum tooling and libraries.
Development Environment: Smart contracts are written in Solidity version 0.8.28, utilizing the latest language features and security improvements. Foundry framework provides fast compilation, testing, and deployment capabilities. Forge unit tests ensure comprehensive contract testing with gas optimization analysis. Foundry deployment scripts enable repeatable, version-controlled deployments.
Security Patterns and Architecture: UUPS (Universal Upgradeable Proxy Standard) enables safe contract upgrades while preserving user data and funds. OpenZeppelin AccessControl provides battle-tested role-based permission systems. ReentrancyGuard and Pausable contracts prevent common attack vectors. Modular contract composition enables clean separation of concerns.
Contract Architecture Principles: The main Fund contract inherits from multiple specialized contracts to provide comprehensive functionality. Initializable pattern enables proxy-based upgrades while preventing multiple initialization. Access control roles include admin for high-level management, controller for operational functions, and strategy roles for yield management.
Blockchain Client Infrastructure
The Wafra platform interacts with blockchain networks through modern, TypeScript-native libraries that provide type safety and performance optimization.
Library Selection and Benefits: Viem provides a TypeScript-native Ethereum library with superior performance and developer experience compared to traditional libraries. Wagmi offers React hooks for Ethereum that integrate seamlessly with the React Native application. Custom blockchain utilities provide Wafra-specific functionality while leveraging proven libraries.
Provider Configuration and Redundancy: Multiple RPC providers including Alchemy and Infura ensure high availability for mainnet operations. Base Sepolia public RPC provides testnet access for development and testing. Fallback provider redundancy prevents service disruption when individual providers experience issues.
Performance and Type Safety Features: Full TypeScript integration provides compile-time safety for all contract interactions. Intelligent query caching and deduplication reduce unnecessary network requests. Real-time transaction tracking provides immediate feedback on transaction status. Dynamic gas management ensures transactions confirm reliably while minimizing costs.
Client Configuration: Public client configuration enables reading blockchain state with batched requests for efficiency. Wallet client configuration enables transaction signing and submission. Contract instances include full ABI typing for compile-time safety. Environment-specific configuration supports both testnet and mainnet operations.
Development Tools & Infrastructure
Monorepo Management
Wafra uses Turborepo for efficient monorepo management, enabling coordinated development across multiple applications and packages.
Build System Optimization: Turborepo provides incremental builds that only rebuild changed packages and their dependents. Intelligent caching stores build artifacts to avoid redundant work. Parallel task execution maximizes development and CI performance. Remote caching support enables shared build artifacts across team members and CI systems.
Package Management Strategy: PNPM package manager provides 3x faster installation compared to npm through efficient dependency resolution. Automatic dependency deduplication reduces disk usage and installation time. Workspace management enables shared dependencies across packages while maintaining isolation where needed.
Code Sharing Architecture: Shared TypeScript packages provide common functionality across applications. Utility libraries contain reusable functions and helpers. Shared type definitions ensure consistency across the entire codebase. Configuration packages provide consistent linting, TypeScript, and build configurations.
Project Organization: The monorepo is organized into apps containing deployable applications, packages containing shared libraries, and tools containing development utilities. This structure enables clear separation of concerns while facilitating code sharing and consistency.
Development Experience
Wafra prioritizes developer experience through comprehensive tooling and automation.
Code Quality and Consistency: ESLint provides TypeScript and React-specific linting rules to catch errors early. Prettier ensures consistent code formatting across the entire codebase. Husky pre-commit hooks prevent low-quality code from entering the repository. Comprehensive type checking prevents runtime errors through compile-time validation.
TypeScript Configuration: Strict type checking is enabled across all packages to catch potential issues early. Absolute imports with @ prefix provide clean, maintainable import statements. Shared TypeScript configuration ensures consistency across all applications and packages.
Testing Strategy: Vitest provides fast unit testing with excellent TypeScript integration and hot reloading. Supertest enables comprehensive API integration testing. Foundry provides specialized smart contract testing with gas optimization analysis. React Native Testing Library ensures mobile components work correctly.
Development Tools: Full source map support enables effective debugging in development environments. Hot reloading provides immediate feedback during development. Structured logging with Pino provides clear insight into application behavior. Development environment configuration supports local database and blockchain testing.
Infrastructure & Deployment
Development Environment
The development environment provides a complete local testing environment that mirrors production capabilities.
Local Development Stack: PostgreSQL database runs via Docker containers for consistent development environments. Hardhat local blockchain node provides fast, deterministic testing environment. Payment provider sandbox environments enable safe testing of financial integrations. Local Socket.IO server supports real-time features during development.
Development Tools and Workflow: Yarn workspaces manage monorepo dependencies and provide consistent package management. TypeScript provides type safety throughout the entire development process. Code quality tools including ESLint, Prettier, and Husky ensure consistent code standards. Comprehensive testing suite includes Jest for JavaScript, Hardhat for smart contracts, and React Native Testing Library for mobile components.
Production Infrastructure
The production environment is designed for scalability, reliability, and security.
Backend Deployment Architecture: Scalable Node.js hosting provides automatic scaling based on traffic demands. Managed PostgreSQL with replication ensures data durability and high availability. Base network integration provides reliable blockchain connectivity. Comprehensive logging and alerting enable proactive issue resolution.
Frontend Deployment Strategy: Web applications are currently deployed on Railway with plans to migrate to CDN for improved global performance. Mobile applications will be distributed through standard app stores with over-the-air updates for rapid deployment. Static assets are optimized and cached for fast global delivery.
Security Infrastructure
Production security implements multiple layers of protection:
Network-Level Security: TLS 1.3 encryption protects all data in transit between clients and servers. Rate limiting prevents abuse and protects against DDoS attacks. Geographic DDoS protection through Cloudflare provides global protection against attacks.
Application-Level Security: Input validation and sanitization prevent injection attacks and data corruption. SQL injection prevention through parameterized queries and ORM usage. XSS protection through proper output encoding and Content Security Policy.
Blockchain-Level Security: Multisig wallet controls prevent single points of failure for fund management. Emergency pause functionality enables rapid response to security incidents. Comprehensive smart contract testing and auditing ensure contract security.
Data Protection: Encryption at rest protects sensitive data stored in databases. Secure key management through HSM integration. Comprehensive audit logging tracks all sensitive operations for compliance and security analysis.
This comprehensive technology stack provides a solid foundation for building, scaling, and maintaining the Wafra platform while ensuring security, performance, and developer productivity across all components of the system.