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

# 4. Technical Architecture

#### 4.1 Stack Overview

FLUX is built on modern, production-ready technologies:

| Layer                      | Technology                                    | Purpose                                               |
| -------------------------- | --------------------------------------------- | ----------------------------------------------------- |
| **Frontend**               | Next.js 16 (App Router), React 19, TypeScript | User interface and client logic                       |
| **Styling**                | Tailwind CSS, Radix UI, shadcn components     | Accessible, responsive design                         |
| **Charts & Visualization** | Recharts, Sonner (toasts)                     | Real-time metrics and notifications                   |
| **Backend**                | Next.js Route Handlers, TypeScript            | API logic and agent orchestration                     |
| **Database**               | MongoDB (official Node driver)                | Persistent state for users, agents, runs, and metrics |
| **Wallet Management**      | Privy (@privy-io/node)                        | Embedded wallet provisioning and control              |
| **On-Chain Integration**   | viem, wagmi, RainbowKit, WalletConnect        | Transaction signing, state reads, and wallet UX       |
| **External APIs**          | Uniswap Trading & Liquidity APIs              | Quote generation and execution                        |
| **Background Jobs**        | Vercel cron routes                            | Agent ticks, pool polling, arena rebuilds             |
| **LLM Integration**        | OpenAI                                        | Optional model-assisted price-box selection           |
| **Configuration**          | Zod                                           | Environment validation and type safety                |

#### 4.2 Data Model

**Users & Sessions**

* Session model gates all API access; users can only read/write their own agents and data
* Multi-chain support with wallet provisioning tied to user identity

**Agents**

Stored documents capture:

* Configuration (pool, chain, strategy parameters)
* Execution mode (quote-only or broadcast)
* State (active, paused, completed, failed)
* Associated runs and receipts

**Agent Runs**

Each tick generates a run record containing:

* Timestamp and input state (pool price, reserves, user config)
* Decision outcome (should trade or skip)
* Quote details (amount, slippage, estimated gas)
* Broadcast status (pending, confirmed, reverted)

**Trading Audit**

Fine-grained audit rows track:

* Each trading attempt with full decision trail
* Quote generation and validation steps
* On-chain receipt confirmation

**Metrics & Rollups**

Aggregated metrics enable efficient dashboard queries:

* Per-pool fill rates and slippage
* Agent performance over time windows
* Comparative analytics for the arena

**Lab Pools**

Experimental pool configurations for the Liquidity Lab, supporting v4-style state exploration

#### 4.3 Wallet Management

**Embedded Wallets via Privy**

* **Authorization Model**: A server-controlled authorization private key provisions per-agent wallets
* **Flexible Signing**: Support for both agent-dedicated wallets and user-scoped signer models
* **Policy Integration**: Optional policy IDs enforce additional on-chain constraints
* **Custody**: Wallets are non-custodial; users retain control through configured authorization schemes

**User Wallet Integration**

For the Liquidity Lab and advanced workflows:

* **RainbowKit + WalletConnect**: Multi-wallet support with Reown project integration
* **viem & wagmi**: Low-level transaction signing and on-chain reads

#### 4.4 Uniswap Integration

**Trading API**

* Quote generation for proposed trades
* Stable error codes and consistent retry logic
* Throttling and backoff for production stability

**Liquidity API**

* LP position queries and state reads
* Advanced liquidity provision workflows
* Integration with existing Uniswap infrastructure

**Unified HTTP Layer**

A shared HTTP adapter provides:

* Consistent error handling and retry strategies
* Universal Router version alignment between quote and swap operations
* Authenticated access with stable API keys

#### 4.5 Background Jobs & Orchestration

**Agent Ticks**

Vercel cron-style routes trigger periodic agent evaluations:

* Configurable tick frequency per agent
* Optional LLM-assisted decision-making
* Fallback to rule-based execution if LLM unavailable

**Pool Polling**

Background jobs refresh pool state:

* Reserve and price snapshots
* Liquidity distribution updates
* Support for subgraph queries with JSON-RPC fallback

**Arena Rebuilds**

Periodic recalculation of leaderboards and comparative metrics

**Receipt Polling**

Monitors on-chain settlement:

* Chainlink-style spot anchors for validation
* Fallback JSON-RPC mechanisms when subgraph data is unavailable

#### 4.6 Configuration & Environment

All environment variables are validated via Zod in a single server module:

* Chain RPC endpoints
* Uniswap API credentials
* Privy authorization keys
* OpenAI API keys (if using model-assisted features)
* Vercel cron secrets

This ensures type-safe configuration and early detection of missing or invalid settings.

#### 4.7 Build & Deployment Optimization

A pragmatic fix in `next.config.mjs` pins Turbopack's workspace root to prevent Next.js from accidentally treating a stray lockfile in a parent monorepo directory as the root. This avoids:

* Broken chunk URLs in development
* Router noise and rebuild issues
* Monorepo configuration conflicts


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://tryflux.gitbook.io/flux-docs/4.-technical-architecture.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
