> For the complete documentation index, see [llms.txt](https://crowdfunding-ugmbcc.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://crowdfunding-ugmbcc.gitbook.io/docs/architecture/system-architecture.md).

# System Architecture

This document provides a comprehensive overview of the CrowdFUNding platform's system architecture, explaining how all components work together to deliver a seamless crowdfunding experience.

### High-Level Architecture Overview

The CrowdFUNding platform follows a modern multi-tier architecture with four main components. Each component is designed to be independently deployable while maintaining seamless integration with others.

{% @mermaid/diagram content="flowchart TB
subgraph Users\["Users"]
Donors\["Donors"]
Creators\["Campaign Creators"]
end

```
subgraph Frontend["Frontend (Next.js)"]
    UI["React UI Components"]
    Wagmi["Wagmi/Viem"]
    API_Client["API Client (Axios)"]
end

subgraph Backend["Backend (Express.js)"]
    REST["REST API"]
    Auth["Auth Service"]
    Sync["Auto-Sync Service"]
    DB[(PostgreSQL)]
end

subgraph Indexer["Indexer (Ponder)"]
    EventHandler["Event Handlers"]
    GraphQL["GraphQL API"]
    IndexerDB[(SQLite/PostgreSQL)]
end

subgraph Blockchain["Base Sepolia"]
    Campaign["Campaign.sol"]
    Badge["Badge.sol"]
    MockSwap["MockSwap.sol"]
    Tokens["IDRX / USDC"]
end

Users --> Frontend
UI --> Wagmi
UI --> API_Client
Wagmi --> |"RPC Calls"| Blockchain
API_Client --> |"REST"| REST
REST --> DB
Sync --> |"Poll Data"| GraphQL
EventHandler --> |"Subscribe"| Blockchain
EventHandler --> IndexerDB
GraphQL --> IndexerDB" %}
```

### Component Architecture

This section describes the internal architecture of each component, explaining the design decisions and technologies used.

#### 1. Frontend Architecture

The frontend is built with Next.js 16 using the App Router pattern, providing server-side rendering for SEO and fast initial page loads.

{% @mermaid/diagram content="flowchart TB
subgraph Pages\["App Router"]
Landing\["/ (Landing)"]
Home\["/home"]
Campaign\["/campaign/:id"]
Donate\["/donate/:id"]
Profile\["/profile"]
Honors\["/honors"]
end

```
subgraph Components["Components"]
    UI["UI Elements"]
    Layout["Layouts"]
    Forms["Forms"]
end

subgraph Hooks["Custom Hooks"]
    useCrowdfunding["useCrowdfunding"]
    useCreateCampaign["useCreateCampaign"]
    useDonate["useDonate"]
    useWithdraw["useWithdraw"]
end

subgraph Services["Services"]
    Wagmi["Wagmi Config"]
    APIClient["Backend API"]
    GoogleOAuth["Google OAuth 2.0"]
end

Pages --> Components
Pages --> Hooks
Hooks --> Services" %}
```

The following table summarizes the key architectural decisions in the frontend:

| Layer                | Technology                    | Purpose                                    |
| -------------------- | ----------------------------- | ------------------------------------------ |
| **Framework**        | Next.js 16 (App Router)       | Server-side rendering, routing, API routes |
| **State Management** | React Query + Context         | Server state caching, global app state     |
| **Blockchain**       | Wagmi + Viem                  | Type-safe contract interactions            |
| **Authentication**   | Google OAuth 2.0 + RainbowKit | Social login + Web3 wallet connection      |
| **Styling**          | TailwindCSS 4                 | Utility-first responsive design            |

#### 2. Backend Architecture

The backend uses a layered architecture pattern, separating concerns between routes, controllers, services, and data access layers. It also serves as a caching layer to reduce direct blockchain queries.

{% @mermaid/diagram content="flowchart TB
subgraph API\["API Layer"]
Routes\["Express Routes"]
Middleware\["Auth Middleware"]
end

```
subgraph Business["Business Layer"]
    VaultController["Vault Controller"]
    AuthController["Auth Controller"]
    SyncController["Sync Controller"]
    AchievementController["Achievement Controller"]
end

subgraph Data["Data Layer"]
    Models["Sequelize Models"]
    PonderClient["Ponder API Client"]
end

subgraph External["External"]
    PostgreSQL[(PostgreSQL)]
    Ponder["Ponder Indexer"]
    Blockchain["Base Sepolia"]
end

Routes --> Middleware
Middleware --> Business
Business --> Data
Models --> PostgreSQL
PonderClient --> Ponder
SyncController --> PonderClient" %}
```

The backend serves multiple critical functions as described in this table:

| Service          | Responsibility          | Key Features                       |
| ---------------- | ----------------------- | ---------------------------------- |
| **REST API**     | Serve frontend requests | CORS, rate limiting, validation    |
| **Auth Service** | User authentication     | Google OAuth, JWT tokens, sessions |
| **Sync Service** | Cache blockchain data   | 30-second polling from Ponder      |
| **Database**     | Store off-chain data    | User profiles, campaign metadata   |

#### 3. Smart Contract Architecture

The smart contracts follow a singleton pattern where one contract manages all campaigns, optimizing gas costs and simplifying event indexing.

{% @mermaid/diagram content="flowchart LR
subgraph Core\["Core Contracts"]
Campaign\["Campaign.sol (Singleton)"]
Badge\["Badge.sol (NFT Factory)"]
end

```
subgraph Support["Support Contracts"]
    MockSwap["MockSwap.sol"]
    IDRX["MockIDRX.sol"]
    USDC["MockUSDC.sol"]
end

subgraph Libraries["OpenZeppelin"]
    ReentrancyGuard["ReentrancyGuard"]
    SafeERC20["SafeERC20"]
    ERC721["ERC721"]
end

Campaign --> MockSwap
Campaign --> IDRX
MockSwap --> IDRX
MockSwap --> USDC
Campaign --> ReentrancyGuard
Campaign --> SafeERC20
Badge --> ERC721" %}
```

Key design decisions for the smart contracts are summarized below:

| Pattern           | Implementation           | Benefit                       |
| ----------------- | ------------------------ | ----------------------------- |
| **Singleton**     | One Campaign.sol for all | Saves gas, centralized events |
| **Auto-Swap**     | Built into donate()      | UX simplification             |
| **Unified Token** | All stored as IDRX       | Simplified accounting         |

#### 4. Indexer Architecture

The Ponder indexer listens to blockchain events and maintains a queryable database, providing both GraphQL and REST APIs for data access.

{% @mermaid/diagram content="flowchart TB
subgraph Blockchain\["Blockchain Events"]
CampaignCreated\["CampaignCreated"]
DonationReceived\["DonationReceived"]
FundWithdrawn\["FundWithdrawn"]
BadgeMinted\["BadgeMinted"]
end

```
subgraph Handlers["Event Handlers"]
    CampaignHandler["Campaign.ts"]
    BadgeHandler["Badge.ts"]
end

subgraph Database["Database"]
    Campaigns["campaigns"]
    Donations["donations"]
    Withdrawals["withdrawals"]
    Badges["badges"]
end

subgraph APIs["APIs"]
    GraphQL["GraphQL Endpoint"]
    REST["REST Endpoints"]
end

Blockchain --> Handlers
Handlers --> Database
Database --> APIs" %}
```

The indexer handles the following events and stores them in structured tables:

| Event              | Handler                           | Stored Data              |
| ------------------ | --------------------------------- | ------------------------ |
| `CampaignCreated`  | Insert campaign                   | id, name, owner, target  |
| `DonationReceived` | Insert donation, update balance   | donor, amount, timestamp |
| `FundWithdrawn`    | Insert withdrawal, update balance | owner, amount            |
| `BadgeMinted`      | Insert badge                      | tokenId, owner, name     |

***

### Data Flow Architecture

This section explains how data moves through the system during key operations.

#### Campaign Creation Flow

When a user creates a campaign, data flows through multiple layers before being stored on the blockchain and cached locally.

{% @mermaid/diagram content="sequenceDiagram
participant User
participant Frontend
participant Wallet
participant Contract as Campaign.sol
participant Indexer
participant Backend
participant DB as PostgreSQL

```
User->>Frontend: Fill campaign form
Frontend->>Wallet: Request signature
Wallet->>Contract: createCampaign(name, creator, target)
Contract-->>Contract: Store CampaignStruct
Contract->>Indexer: Emit CampaignCreated event
Indexer->>Indexer: Index campaign data
Note over Backend: Every 30 seconds
Backend->>Indexer: Poll for new data
Indexer-->>Backend: Return campaigns
Backend->>DB: Upsert campaign cache" %}
```

#### Donation Flow with Auto-Swap

Donations support multiple currencies (BASE, USDC, IDRX) with automatic conversion to IDRX. This simplifies the user experience while ensuring all campaigns receive funds in a stable, predictable currency.

{% @mermaid/diagram content="sequenceDiagram
participant Donor
participant Frontend
participant Contract as Campaign.sol
participant Swap as MockSwap.sol
participant IDRX as IDRX Token

```
Donor->>Frontend: Select currency & amount
alt Native BASE
    Frontend->>Contract: donate(campaignId) + ETH value
    Contract->>Swap: swapETHForToken(IDRX)
    Swap->>IDRX: Transfer IDRX to Campaign
else ERC20 Token
    Frontend->>Contract: donate(campaignId, amount, tokenAddress)
    Contract->>Swap: swap(tokenIn, IDRX, amount)
    Swap->>IDRX: Transfer IDRX to Campaign
end
Contract-->>Contract: campaign.balance += idrxAmount
Contract->>Frontend: Emit DonationReceived" %}
```

***

### Communication Protocols

The platform uses different protocols optimized for each type of communication.

#### Protocol Summary

This table describes the communication methods between each component:

| From     | To         | Protocol             | Purpose                         |
| -------- | ---------- | -------------------- | ------------------------------- |
| Frontend | Blockchain | JSON-RPC (via Wagmi) | Contract calls, transactions    |
| Frontend | Backend    | REST (Axios)         | User data, off-chain operations |
| Backend  | Indexer    | REST/GraphQL         | Fetch indexed blockchain data   |
| Indexer  | Blockchain | WebSocket/RPC        | Event subscription              |
| Backend  | PostgreSQL | TCP (pg driver)      | Data persistence                |

#### API Endpoint Categories

The backend exposes the following REST API categories:

| Category       | Base Path                      | Purpose                |
| -------------- | ------------------------------ | ---------------------- |
| Authentication | `/crowdfunding/auth/*`         | Login, logout, session |
| Campaigns      | `/crowdfunding/vault/*`        | CRUD operations        |
| Contributions  | `/crowdfunding/contribution/*` | Donation tracking      |
| Achievements   | `/crowdfunding/achievements/*` | Badge management       |
| Sync           | `/api/sync/*`                  | Data synchronization   |

***

### Security Architecture

Security is implemented at every layer of the stack to protect user funds and data.

#### Security Layers

{% @mermaid/diagram content="flowchart TB
subgraph Frontend\["Frontend Security"]
HTTPS\["HTTPS Only"]
CSP\["Content Security Policy"]
WalletAuth\["Wallet Signatures"]
end

```
subgraph Backend["Backend Security"]
    JWT["JWT Authentication"]
    RateLimit["Rate Limiting"]
    InputVal["Input Validation"]
    CORS["CORS Configuration"]
end

subgraph Blockchain["Smart Contract Security"]
    Reentrancy["ReentrancyGuard"]
    SafeTransfer["SafeERC20"]
    OwnerCheck["Owner Validation"]
    Overflow["Overflow Protection"]
end" %}
```

The following table summarizes security measures at each layer:

| Layer              | Threat              | Mitigation                   |
| ------------------ | ------------------- | ---------------------------- |
| **Frontend**       | XSS, CSRF           | CSP headers, secure cookies  |
| **Backend**        | SQL Injection       | Parameterized queries        |
| **Backend**        | Unauthorized access | JWT + session validation     |
| **Smart Contract** | Reentrancy          | OpenZeppelin ReentrancyGuard |
| **Smart Contract** | Token theft         | SafeERC20, owner checks      |

***

### Scalability Considerations

The architecture is designed to scale horizontally at each layer:

| Component    | Scaling Strategy                               |
| ------------ | ---------------------------------------------- |
| **Frontend** | Vercel Edge Functions, CDN                     |
| **Backend**  | Horizontal pod scaling, load balancer          |
| **Database** | PostgreSQL read replicas                       |
| **Indexer**  | Multiple instances with different block ranges |
