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

# Architecture

This document provides an overview of TilepMoney's system architecture, including frontend, backend, and smart contract components.

### System Overview

TilepMoney is built as a **full-stack Next.js application** that handles both frontend presentation and backend business logic within a single codebase.&#x20;

All database operations, external API calls, and server-side processing are handled through Next.js API Routes and Server Actions.

<figure><img src="/files/Z9hElDsbdp8xBT8A3Mt5" alt="" width="375"><figcaption></figcaption></figure>

### Frontend Architecture

#### Technology Stack

* **Framework:** Next.js 15 with App Router
* **Language:** TypeScript (strict mode)
* **UI Library:** React 18+
* **Styling:** TailwindCSS + shadcn/ui components
* **Flow Builder:** React Flow (@xyflow/react)
* **State Management:** Zustand
* **Web3:**
  * Privy (authentication)
  * Wagmi (Ethereum interactions)
  * Viem (Low-level Ethereum operations)

#### Key Components

**Workflow Builder:**

* Canvas component using React Flow
* Node palette sidebar (DnD)
* Configuration drawer
* Connection validation logic

**Execution Monitor:**

* Real-time status updates via polling
* Transaction log visualization
* Step-by-step progress tracking

### Backend Architecture

#### API Routes Structure

All backend operations are handled through Next.js API Routes located in `/app/api/`:

**Workflow Management:**

| Method   | Endpoint              | Description           |
| -------- | --------------------- | --------------------- |
| `GET`    | `/api/workflows`      | List all workflows    |
| `GET`    | `/api/workflows/[id]` | Get specific workflow |
| `POST`   | `/api/workflows`      | Create new workflow   |
| `PUT`    | `/api/workflows/[id]` | Update workflow       |
| `DELETE` | `/api/workflows/[id]` | Delete workflow       |

**Workflow Execution:**

| Method | Endpoint                       | Description                                    |
| ------ | ------------------------------ | ---------------------------------------------- |
| `POST` | `/api/workflows/[id]/execute`  | Initiate server-side execution (if applicable) |
| `POST` | `/api/workflows/[id]/simulate` | Run gas estimation and logic checks            |
| `GET`  | `/api/workflows/[id]/status`   | Poll execution status                          |

**Blockchain Operations (Read/Proxy):**

| Method | Endpoint                  | Description                          |
| ------ | ------------------------- | ------------------------------------ |
| `POST` | `/api/blockchain/mint`    | Mint dummy tokens                    |
| `POST` | `/api/blockchain/swap`    | Quote/Execute swap via server wallet |
| `POST` | `/api/blockchain/bridge`  | Initiate bridge transfer             |
| `GET`  | `/api/blockchain/balance` | Fetch token balances                 |

#### Database Schema

**MongoDB Collections:**

**Workflows:**

```typescript
{
  _id: ObjectId,
  name: string,
  description: string,
  nodes: Node[],      // React Flow Node objects
  edges: Edge[],      // React Flow Edge objects (formerly connections)
  userId: string,
  createdAt: Date,
  updatedAt: Date
}
```

**Executions:**

```typescript
{
  _id: ObjectId,
  workflowId: ObjectId,
  status: 'running' | 'finished' | 'failed',
  startedAt: Date,
  finishedAt?: Date,
  logs: LogEntry[],
  txHashes: string[]
}
```

### Smart Contract Architecture

The core of TilepMoney's reliability is the **MainController** smart contract, which atomically orchestrates the entire workflow.

#### Contract Structure

```
src/
├── core/
│   └── MainController.sol      # Main entrance for all workflows
├── actions/
│   ├── SwapAction.sol          # DEX logic
│   ├── YieldAction.sol         # Yield Deposit/Withdraw logic
│   └── BridgeAction.sol        # Cross-chain logic
└── interfaces/
    └── IAdapter.sol            # Standard interface for DeFi protocols
```

#### Main Controller

The `MainController` accepts an array of **Actions**, encoded efficiently, and executes them in sequence. If any action fails (e.g., high slippage, insufficient liquidity), the entire transaction reverts.

* **depositToYield()** - Route funds to Aave/Compound/InitCapital
* **withdrawFromYield()** - Liquidate positions
* **executeSwap()** - Route through 1inch/MerchantMoe
* **bridgeAsset()** - Dispatch via LayerZero/Hyperlane

#### Data Flow

1. **Design**: User builds graph in Frontend.
2. **Compile**: Frontend converts Graph -> Action\[] struct.
3. **Simulate**: `eth_call` to MainController to preview state changes.
4. **Execute**: User signs ONE transaction to `MainController.executeWorkflow(actions)`.
5. **Monitor**: Backend indexes the transaction and updates the UI.

### Security Architecture

* **Authentication**: Wallet-based Auth via Privy.
* **Non-Custodial**: The backend never holds user funds. The MainController relies on `msg.sender` being the user.
* **Input Validation**: API routes validate schema (Zod); Smart Contracts validate balances and allowances.


---

# 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:

```
GET https://tilepmoney.gitbook.io/tilepmoney-docs/core-concepts/architecture.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
