Architecture Overview
SFLUV is built as a modern web application with blockchain integration, consisting of three main services and three PostgreSQL databases.This architecture ensures security, scalability, and transparency while maintaining blockchain integration for all currency transactions.
System Components
Frontend Application
The user-facing web application built with modern React technologies. Technology Stack:- Next.js 15 - React framework with App Router
- React 19 - Latest React with concurrent features
- Tailwind CSS - Utility-first styling
- Radix UI - Accessible component primitives
- Privy - Wallet authentication and management
- Permissionless SDK - Account abstraction and smart accounts
- ethers.js & viem - Ethereum blockchain interaction
- Server-side rendering for performance
- Turbo mode for faster builds and development
- Embedded wallet support through Privy
- Smart account creation via bundler client
- QR code generation for merchant payments
Backend API Server
Go-based REST API handling all business logic, authentication, and database operations. Technology Stack:- Go 1.24 - Modern, compiled language for performance
- chi router - Lightweight HTTP router
- pgx - PostgreSQL driver with connection pooling
- Privy JWT - Token-based authentication
- Mailgun - Transactional email service
- JWT authentication via Privy
- Role-based access control with middleware guards
- Three database connections (app, bot, ponder)
- Background services (faucet bot, affiliate scheduler)
- W9 webhook integration for compliance
- Email notifications for workflow events
Ponder Blockchain Indexer
Real-time blockchain event monitoring and indexing service. Technology Stack:- Ponder - TypeScript blockchain indexer framework
- Berachain RPC - Connection to Berachain network
- PostgreSQL - Event storage
- Listens to ERC20 token events (Transfer, Approval)
- Indexes all SFLUV token transactions
- Stores events in dedicated
ponderdatabase - Sends webhook callbacks to backend API
- Enables transaction history and balance queries
Database Architecture
SFLUV uses three separate PostgreSQL databases for data isolation and performance.App Database
The primary database for all application data. Key Tables:users- User profiles, roles, email verificationproposers- Proposer status and approvalimprovers- Improver status, credentials, primary rewards accountsupervisors- Supervisor assignments and approvalsvoters- Voter eligibilityissuers- Credential issuer scopesworkflows- Complete workflow definitionsworkflow_steps- Individual step data and statusworkflow_roles- Custom roles with credential requirementsworkflow_votes- Vote records for approvalworkflow_deletion_proposals- Deletion vote proposalscredentials- User credentials and grantscredential_types- Available credential typeslocations- Merchant locations and approval statuswallets- User wallet connectionscontacts- User contact listsaffiliates- Affiliate organization data
Bot Database
Manages faucet operations and redemption codes. Key Tables:events- Faucet distribution eventscodes- Redemption codes for eventsredemptions- Code redemption recordsw9_submissions- Tax form submissions for compliancew9_transactions- Transaction tracking for W9 limits
Ponder Database
Blockchain event data indexed by Ponder. Key Tables:Transfer- All ERC20 transfer eventsApproval- All ERC20 approval events
- Transaction history queries
- Balance calculations at specific timestamps
- Merchant payment subscription tracking
Authentication Flow
SFLUV uses Privy for wallet-based authentication with JWT tokens.User Connects Wallet
Frontend calls Privy SDK’s
login() method:- User selects wallet provider or email login
- Privy handles authentication
- User object returned with
userDid(decentralized identifier)
Frontend Requests Access Token
On authenticated API requests:Privy returns a JWT token signed with the app secret
Backend Validates Token
All API routes pass through Middleware:
AuthMiddleware:- Validates JWT signature using Privy verification key
- Extracts
userDidfrom token - Injects
userDidinto request context
API Route Structure
The backend exposes REST endpoints organized by role and functionality.User Routes
Workflow Routes (Proposer)
Workflow Routes (Improver)
Voting Routes
Issuer Routes
Admin Routes
Middleware Guards
Access control is enforced through middleware functions inrouter/router.go:
| Middleware | Access Level | Admin Bypass |
|---|---|---|
withAuth() | Any authenticated user | N/A |
withProposer() | Approved proposers | ✅ |
withImprover() | Approved improvers | ✅ |
withVoter() | Approved voters | ✅ |
withIssuer() | Approved issuers | ✅ |
withSupervisor() | Approved supervisors | ✅ |
withAffiliate() | Approved affiliates | ✅ |
withAdmin() | Admin users only | N/A |
Admin users automatically bypass all role checks except admin-only routes. This allows admins to access any feature for support purposes.
Workflow State Machine
Workflows progress through a well-defined state machine: State Descriptions:- pending - Awaiting voter approval (expires after 14 days)
- approved - Approved by voters, waiting for start_at time
- rejected - Denied by voters
- expired - Pending for >14 days without finalization
- blocked - Part of series waiting for previous workflow payout
- in_progress - Started and accepting step claims
- completed - All steps completed, awaiting payout
- paid_out - All bounties distributed
- deleted - Removed via deletion proposal
Workflow Step State Machine
Individual workflow steps follow their own progression: Step States:- locked - Previous step not yet completed
- available - Ready to be claimed by improvers
- in_progress - Claimed and started by an improver
- completed - Work submitted and approved
- paid_out - Bounty transferred to improver
Steps unlock sequentially. Completing step N automatically makes step N+1 available for claiming.
Voting System Implementation
The democratic voting system uses these rules: Quorum Calculation:Background Services
Two background services run as goroutines:BotService
Purpose: Manage faucet distributions and redemption codes Operations:- Create distribution events
- Generate unique redemption codes
- Process code redemptions
- Track faucet balance
- Handle affiliate event payouts
AffiliateScheduler
Purpose: Process recurring affiliate payouts Operations:- Run on schedule (configurable intervals)
- Calculate affiliate earnings
- Process batch payouts
- Log payout history
main.go and maintain their own error handling and logging.
Credential System
Credentials qualify improvers for specialized workflow roles. Built-in Credential Types:dpw_certified- Department of Public Works certificationsfluv_verifier- Platform verification credential
- Improver requests credential via
/improvers/credential-requests - Request appears in issuer queue at
/issuers/credential-requests - Issuer with appropriate scope reviews and decides
- If approved, credential is granted and visible to workflow system
- Improver can now claim steps requiring that credential
W9 Compliance System
For converting SFLUV tokens to USD (“unwrapping”), users must complete W9 tax forms. Integration:- W9 forms submitted via WordPress integration
- Webhook posts to
/w9/webhookwithW9_WEBHOOK_SECRET - Submissions stored in
bot.w9_submissions - Admin reviews and approves at
/admin/w9/pending
Technology Choices
Why Go for Backend?
- Performance - Compiled language with excellent concurrency
- Type Safety - Strong typing prevents runtime errors
- Standard Library - Built-in HTTP server and tooling
- Deployment - Single binary with no dependencies
- pgx Driver - High-performance PostgreSQL with connection pooling
Why Next.js for Frontend?
- React 19 - Latest features with concurrent rendering
- App Router - Modern routing with server components
- Performance - Server-side rendering and static generation
- TypeScript - Type safety across the entire frontend
- Turbo Mode - Faster builds and hot reload
Why Privy for Auth?
- Wallet Integration - Seamless connection to Ethereum wallets
- Embedded Wallets - Create wallets for non-crypto users
- Email Login - Lower barrier to entry
- JWT Tokens - Standard bearer token authentication
- Security - Industry-standard cryptographic verification
Why Three Databases?
- Isolation - Separate concerns (app, bot, blockchain data)
- Performance - Optimize each database for its workload
- Ponder Stability - Blockchain indexer has its own schema
- Backup Strategy - Different backup requirements per database
Deployment Considerations
Environment Variables Required: Backend (.env):Security Features
JWT Authentication
All API requests validated with Privy-signed JWT tokens
Role-Based Access
Middleware guards prevent unauthorized access to role-specific features
Webhook Validation
W9 webhooks require secret token validation
Admin Key Support
Scripted admin operations use separate API key authentication
Scalability Considerations
- Database Connection Pooling - pgx maintains connection pools for each database
- Goroutine Concurrency - Background services run without blocking main server
- Blockchain Indexing - Ponder handles event indexing separately from main app
- API Rate Limiting - Can be added via chi middleware if needed
- Horizontal Scaling - Stateless backend can run multiple instances behind load balancer