Skip to content

这是一份针对 Next.js 16 + React 19 的最新版完整技术开发文档。

这份文档是为了适配当前(2025年)最新的技术标准而设计的。你可以将它视为你的**“项目蓝图”**。文档中的 “AI 编程指令 (Prompts)” 部分是专门为你使用 AI IDE (如 Cursor, Windsurf, Trae) 准备的,直接复制粘贴即可让 AI 生成高质量代码。


📘 Project ChainEstate: 物业收支存证系统 (v2025)

1. 项目愿景 (Vision)

构建一个符合国内监管要求的、基于 Base 链 的物业财务透明化系统。

  • 核心理念: 链下记账(SQLite),链上存证(Hash)。
  • 合规策略: 法币结算,去 Token 化,管理员代付 Gas。
  • 用户体验: 极简 Web 界面,微信扫码即用,无感知 Web3。

2. 核心技术栈 (Tech Stack) - Next.js 16 标准

模块选型关键特性 / 版本
全栈框架Next.js 16App Router, Async Request APIs, Turbopack
核心库React 19Actions (useActionState), Server Components
语言TypeScript5.x+, 严格类型安全
UI 组件shadcn/ui基于 Tailwind CSS,高度可定制
数据库SQLite配合 Prisma ORM,轻量级,适合独立开发
区块链Base ChainEVM L2,低成本,高安全性
合约交互Ethers.js v6服务端签名 (Wallet),客户端查询 (JsonRpcProvider)
开发环境Hardhat智能合约编译与部署

3. 系统架构 (Architecture)

3.1 数据流向:Gasless 上链模式

利用 Next.js 的 Server Actions 作为安全屏障,私钥永远不离开服务器。

mermaid
sequenceDiagram
    participant User as 业主/前端 (React 19)
    participant Server as Next.js Server Action
    participant DB as SQLite (Prisma)
    participant Chain as Base Chain (EstateLedger)

    User->>Server: 提交表单 (FormData)
    Note right of User: 使用 useActionState 提交
    
    Server->>DB: 1. 写入原始数据 (Status: PENDING)
    Server->>Server: 2. 计算 SHA256 Hash
    Server->>Server: 3. 加载管理员私钥
    Server->>Chain: 4. 调用合约 addRecord(Hash, Amount...)
    
    Chain-->>Server: 5. 返回 Transaction Hash
    
    Server->>DB: 6. 更新 TX Hash (Status: CONFIRMED)
    Server-->>User: 7. 返回成功状态 & 刷新页面

4. 数据库与合约设计

4.1 Prisma 模型 (schema.prisma)

prisma
datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model Record {
  id          Int      @id @default(autoincrement())
  title       String
  amount      Float
  category    String   // 收入 | 支出
  detail      String?
  
  // 存证核心
  docHash     String   // 业务数据的数字指纹
  txHash      String?  // 链上凭证 (上链成功后回填)
  
  status      String   @default("PENDING") // PENDING | CONFIRMED | FAILED
  createdAt   DateTime @default(now())
}

4.2 智能合约 (EstateLedger.sol)

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";

contract EstateLedger is Ownable {
    // 只存日志,不存状态变量,Gas 最低
    event RecordCreated(string indexed docHash, uint256 amount, string category, uint256 timestamp);

    constructor() Ownable(msg.sender) {}

    function addRecord(string memory _docHash, uint256 _amount, string memory _category) public onlyOwner {
        emit RecordCreated(_docHash, _amount, _category, block.timestamp);
    }
}

5. AI 编程指令集 (Prompts for Cursor/Windsurf)

请按顺序将以下 Prompt 发送给你的 AI 编辑器。不要一次性发送所有内容。

🟢 阶段 0:全局设定 (Master Prompt)

复制这段话作为对话的开始,确立 Next.js 16 和 React 19 的上下文。

markdown
Role: You are an expert Full-Stack Web3 Developer specializing in **Next.js 16**, **React 19**, TypeScript, and shadcn/ui.

Project: "ChainEstate" - A Property Management Compliance Ledger on Base Chain.

Tech Stack Standards:
1.  **Framework:** Next.js 16 (App Router).
2.  **State Management:** React 19 Hooks (`useActionState`, `useFormStatus`).
3.  **UI:** shadcn/ui + Tailwind CSS.
4.  **Database:** SQLite + Prisma.
5.  **Blockchain:** Hardhat + Ethers.js v6.

Key Constraints:
- Use **Server Actions** for all blockchain interactions.
- **Async Request APIs:** In Next.js 16, `params` and `searchParams` are promises (e.g., `const { id } = await params`).
- **Private Key Security:** Never expose the Admin Private Key to the client components.
- **Verification:** Users verify data by comparing local Hash vs On-chain Event Log.

🟢 阶段 1:项目初始化与 shadcn

任务:搭建脚手架。

markdown
Step 1: Initialization

1. Initialize a new Next.js 16 project (if not already done).
2. Setup **shadcn/ui**:
   - Provide commands to add: `button`, `card`, `input`, `label`, `select`, `table`, `badge`, `dialog`, `toast`.
   - Ensure `lucide-react` is installed.
3. Install Dependencies:
   - `npm install ethers dotenv prisma @prisma/client clsx tailwind-merge`
   - `npm install --save-dev hardhat`

Please list the exact terminal commands I need to run.

🟢 阶段 2:合约与数据库层

任务:准备后端数据结构。

markdown
Step 2: Smart Contract & Database

1. **Hardhat Setup:**
   - Create a `blockchain` folder in the root.
   - Initialize Hardhat (TypeScript).
   - Create `contracts/EstateLedger.sol`: Inherit Ownable, define `RecordCreated` event, create `addRecord` function.
   - Create a deploy script targeting Base Sepolia/Mainnet.

2. **Prisma Setup:**
   - Initialize Prisma with SQLite.
   - Create `schema.prisma` with the `Record` model (id, title, amount, category, detail, docHash, txHash, status, createdAt).
   - Generate the migration command.

Please generate the Solidity code and the Prisma schema.

🟢 阶段 3:服务端逻辑 (Server Actions)

任务:编写核心业务逻辑。注意 React 19 的 Action 写法。

markdown
Step 3: Server Actions (React 19 Pattern)

Create `app/lib/actions.ts` with `'use server'`.

Define a Server Action `createRecord`:
- **Signature:** `export async function createRecord(prevState: any, formData: FormData)`
- **Logic:**
  1. Extract `title`, `amount`, `category` from formData.
  2. Create a record in Prisma (Status: PENDING).
  3. Generate SHA256 Hash (`amount + category + timestamp...`).
  4. **Blockchain Write:**
     - Init `ethers.Wallet` with `process.env.PRIVATE_KEY`.
     - Connect to `EstateLedger` contract.
     - Call `addRecord(hash, amount...)`.
     - Wait for 1 block confirmation.
  5. Update Prisma record with `txHash` and Status: CONFIRMED.
  6. Return `{ success: true, message: "Recorded on chain!" }`.
  7. Handle errors: Return `{ success: false, message: error.message }`.

Please generate the robust TypeScript code for this action.

🟢 阶段 4:前端界面 (React 19 Forms)

任务:使用 shadcn 和新版 Hooks。

markdown
Step 4: UI Components (React 19)

1. **RecordForm (`components/record-form.tsx`):**
   - Use `useActionState` hook: `const [state, formAction, isPending] = useActionState(createRecord, initialState)`.
   - Form element: `<form action={formAction}>`.
   - Submit Button: Use `disabled={isPending}` to show loading state.
   - Display `state.message` in a Toast or Alert upon completion.

2. **RecordList (`components/record-list.tsx`):**
   - This is an Async Server Component.
   - Fetch data: `const records = await prisma.record.findMany(...)`.
   - Render a shadcn `Table`.
   - Add a `<VerifyButton record={record} />` (Client Component) to each row.

Please generate these two components using shadcn/ui.

🟢 阶段 5:验证逻辑 (客户端)

任务:实现“不信你查链”。

markdown
Step 5: Client-side Verification

Create `components/verify-button.tsx` (Client Component).

1. **Logic:**
   - Receive the `record` object as a prop.
   - On click, open a Dialog.
   - Use `ethers.JsonRpcProvider` (Public RPC, no keys) to fetch the Transaction Receipt via `record.txHash`.
   - Parse the logs to find `RecordCreated`.
   - **Verification:** Compare `onChainHash` vs `record.docHash`.
2. **UI:**
   - Show "✅ Valid" or "❌ Tampered" inside the Dialog.
   - Provide a link to BaseScan explorer.

Please generate this component code.

6. 部署与运维指南 (Deployment)

由于你选择了 SQLite,传统的 Vercel 免费版部署(Serverless)会有一个问题:每次重新部署,本地的 SQLite 文件会被重置,数据会丢失。

针对独立开发者,你有两个最佳方案:

方案 A:最简单 - 购买轻量服务器 (VPS)

  • 适用: 想要数据完全掌握在自己手里,SQLite 文件持久化。
  • 成本: 腾讯云/阿里云轻量应用服务器(约 ¥50-100/月)。
  • 操作:
    1. 在服务器安装 Node.js 20+ 和 PM2。
    2. 上传代码,运行 npm run buildnpm start
    3. 你的 SQLite 数据库文件 (dev.db) 就安稳地躺在服务器硬盘里,永远不会丢。

方案 B:云端分离 - Vercel + Turso

  • 适用: 想要 Vercel 的极速部署体验,不管理服务器。
  • 成本: 免费(Turso 有慷慨的免费额度)。
  • 操作:
    1. 注册 Turso (一个云端 SQLite 服务)。
    2. 修改 schema.prisma 的 datasource 为 libsql
    3. 代码推送到 GitHub,自动触发 Vercel 部署。
    4. Vercel 运行代码,数据存储在 Turso 云端。

7. 环境变量清单 (.env)

在开始写代码前,请确保你准备好了以下变量:

env
# 数据库 (如果是本地 SQLite)
DATABASE_URL="file:./dev.db"

# 区块链节点 (去 Alchemy 或 QuickNode 申请 Base Mainnet)
NEXT_PUBLIC_RPC_URL="https://base-mainnet.g.alchemy.com/v2/你的KEY"

# 管理员私钥 (钱包里放 0.01 ETH 即可)
PRIVATE_KEY="0x你的私钥..."

# 合约地址 (部署 Hardhat 后获得)
NEXT_PUBLIC_CONTRACT_ADDRESS="0x..."

现在,你可以打开你的编辑器,按照 阶段 0阶段 5 的顺序开始构建了。这将是一个非常酷的、技术前沿的 Web3 落地应用!祝你好运!