Kaynağa Gözat

fix: add clmm-sdk pre-build step and AGENTS.md

Build was failing because clmm-sdk dist/ was not generated. Added
build:sdk script and wired it into the build pipeline. Updated SDK
tsconfig to resolve @types from root node_modules and exclude
test/playground files. Added AGENTS.md for project context.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
zhangchunrui 2 hafta önce
ebeveyn
işleme
5a05752a3b
3 değiştirilmiş dosya ile 129 ekleme ve 4 silme
  1. 117 0
      AGENTS.md
  2. 2 1
      package.json
  3. 10 3
      src/lib/clmm-sdk/tsconfig.json

+ 117 - 0
AGENTS.md

@@ -0,0 +1,117 @@
+# AGENTS.md — Byreal CLMM Copy Trade
+
+Solana 链上 Byreal DEX CLMM 跟单系统。监控目标钱包的集中流动性操作,自动复制 Open / Add / Decrease / Close,支持可配置倍率和金额上限。
+
+## Tech Stack
+
+- **Frontend**: Next.js 16 + React 19 + Tailwind CSS 4 + SWR
+- **Backend**: Next.js API Routes (server-side only)
+- **Database**: SQLite (better-sqlite3, WAL mode)
+- **Blockchain**: Solana Web3.js + Anchor 0.31
+- **CLMM SDK**: 本地 TypeScript SDK,编译为 CommonJS 后通过 `require()` 导入
+- **Swap**: Jupiter Ultra API (ExactIn / ExactOut)
+- **Package Manager**: pnpm
+
+## Project Structure
+
+```
+src/
+├── app/                          # Next.js App Router
+│   ├── page.tsx                  # Dashboard
+│   ├── addresses/page.tsx        # 监控地址管理
+│   ├── positions/page.tsx        # 仓位映射
+│   ├── history/page.tsx          # 操作历史
+│   ├── settings/page.tsx         # 全局设置
+│   └── api/
+│       ├── monitor/{start,stop,status}/  # 监控控制
+│       ├── addresses/route.ts    # 地址 CRUD
+│       ├── positions/route.ts    # 仓位查询 & 手动关仓
+│       ├── history/route.ts      # 历史记录
+│       ├── settings/route.ts     # 设置读写
+│       └── wallet/balance/route.ts
+├── lib/
+│   ├── monitor/                  # 监控服务
+│   │   ├── index.ts              # MonitorService (WebSocket + 轮询, singleton)
+│   │   ├── parser.ts             # TX 解析 (判别符 + 日志 + 事件解码)
+│   │   └── types.ts              # ParsedOperation
+│   ├── copier/                   # 跟单引擎
+│   │   ├── index.ts              # CopyEngine (四种操作调度)
+│   │   ├── price.ts              # Jupiter Price API 价格获取
+│   │   ├── ratio.ts              # 金额缩放 (Decimal.js)
+│   │   └── swap.ts               # Jupiter Ultra swap
+│   ├── db/
+│   │   ├── index.ts              # SQLite singleton (WAL mode)
+│   │   ├── schema.ts             # 4 表 DDL + 自动迁移
+│   │   └── queries.ts            # 20+ SQL helpers
+│   ├── solana/
+│   │   ├── connection.ts         # RPC singleton
+│   │   └── wallet.ts             # Keypair & signerCallback
+│   ├── clmm-sdk/                 # Byreal CLMM SDK (独立编译)
+│   │   ├── src/index.ts          # re-export all
+│   │   ├── src/constants.ts      # Program IDs, tick sizes
+│   │   ├── src/client/           # Chain class (链上操作)
+│   │   ├── src/instructions/     # TX 构建 & 底层布局
+│   │   └── src/utils/            # TickMath, SqrtPrice 等
+│   ├── pool-info.ts              # 池子信息缓存 (1 min TTL)
+│   └── config.ts                 # 环境变量加载
+└── components/layout/            # Sidebar & TopBar
+```
+
+## Build Process
+
+```bash
+pnpm install                      # 安装根依赖
+pnpm build:sdk                    # tsc 编译 clmm-sdk → dist/
+pnpm build                        # build:sdk + next build
+```
+
+**重要**: `clmm-sdk` 是独立编译的 CommonJS 包。根 `tsconfig.json` 通过 `exclude` 排除了它。`copier/index.ts` 通过 `require('../clmm-sdk/dist/index.js')` 导入,而不是 ES import。修改 SDK 源码后必须重新运行 `pnpm build:sdk`。
+
+## Architecture Decisions
+
+### SDK 通过 require() 导入
+`clmm-sdk` 编译为 CommonJS (`"module": "commonjs"`),通过动态 `require()` 加载,避免 Turbopack 尝试打包 SDK 内部依赖。`next.config.ts` 中 `serverExternalPackages: ['better-sqlite3']` 确保 native 模块不被打包。
+
+### 双模式监控
+WebSocket 订阅 Byreal program logs(confirmed 级别)+ 轮询(5s 间隔)。WebSocket 断线自动回退到轮询。签名去重使用 120s TTL 防止内存泄漏。
+
+### 仓位映射
+通过 `position_mappings` 表建立 target_nft_mint → our_nft_mint 的映射关系,跨越四种操作类型追踪仓位对应关系。
+
+### Swap 策略
+- 开仓/加仓: ExactOut 模式,补齐余额缺口 (额外 2% buffer)
+- 关仓: ExactIn 模式,将收到的代币全部换回 USDC
+- 稳定币 (USDC, USDT, USD1) 不触发 swap
+
+## Key Constants
+
+- **Byreal Program ID**: `REALQqNEomY6cQGZJUGwywTBD2UmDT32rZcNnfxQ5N2`
+- **USDC Mint**: `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`
+- **DB Path**: `data/copytrade.db`
+
+## Database Tables
+
+- `watched_addresses` — 监控目标 (address, label, enabled, 单独 multiplier/max_usd)
+- `position_mappings` — target_nft_mint(UNIQUE) ↔ our_nft_mint
+- `copy_history` — 操作日志 (status: pending/executing/success/failed/skipped)
+- `settings` — 全局 key-value 配置
+
+## Environment Variables
+
+```env
+SOL_ENDPOINT          # RPC endpoint (默认 mainnet-beta)
+SOL_SECRET_KEY        # Base58 私钥
+JUPITER_API_KEY       # Jupiter API Key
+COPY_MULTIPLIER       # 跟单倍率 (默认 1.0)
+COPY_MAX_USD          # 单次上限 (默认 1000)
+COPY_SLIPPAGE         # 滑点 (默认 0.02)
+MONITOR_POLL_INTERVAL # 轮询间隔 ms (默认 5000)
+```
+
+## Conventions
+
+- Singleton 模式: MonitorService, CopyEngine, DB connection, RPC connection
+- 所有链上操作在 `src/lib/` server-side 代码中,前端仅通过 API routes 交互
+- SWR 用于前端数据刷新 (5s 间隔)
+- 错误记录到 copy_history 表 + MonitorService.errorLog (最近 50 条)
+- Slippage: 减仓/关仓用 99%(宽松,移除自有流动性),开仓/加仓用 2%(保守)

+ 2 - 1
package.json

@@ -4,7 +4,8 @@
   "private": true,
   "scripts": {
     "dev": "next dev",
-    "build": "next build",
+    "build:sdk": "tsc -p src/lib/clmm-sdk/tsconfig.json --typeRoots node_modules/@types",
+    "build": "pnpm build:sdk && next build",
     "start": "next start",
     "lint": "eslint",
     "format": "prettier --write \"src/**/*.{ts,tsx,css}\""

+ 10 - 3
src/lib/clmm-sdk/tsconfig.json

@@ -1,7 +1,7 @@
 {
   "compilerOptions": {
     "types": ["node"],
-    "typeRoots": ["./node_modules/@types"],
+    "typeRoots": ["./node_modules/@types", "../../node_modules/@types"],
     "lib": ["es2022"],
     "module": "commonjs",
     "outDir": "./dist",
@@ -9,10 +9,17 @@
     "esModuleInterop": true,
     "moduleResolution": "node",
     "resolveJsonModule": true,
-    "strict": false,         
-    "noImplicitAny": false,  
+    "strict": false,
+    "noImplicitAny": false,
+    "noEmitOnError": false,
     "skipLibCheck": true,
     "declaration": true,
     "declarationMap": true
   },
+  "exclude": [
+    "node_modules",
+    "dist",
+    "src/playgrounds",
+    "src/**/*.test.ts"
+  ]
 }