feat: Add initial strategic planning, UX design, and verification artifacts, define a new AI-powered crypto assistant epic, update existing epics, and disable SSL for local database connection.

This commit is contained in:
API Test Bot 2026-02-02 17:43:33 +07:00
parent f21e1a5b58
commit f2e38c52a1
17 changed files with 7028 additions and 739 deletions

View file

@ -0,0 +1,800 @@
# Epic 1: Trợ lý Crypto AI trên Trình duyệt
**Trạng thái:** ✅ ĐÃ HOÀN THÀNH
**Giai đoạn:** Phase 1
**Thời gian:** 2 tuần
**Mức độ ưu tiên:** P0 (Nghiêm trọng)
---
## Tổng quan Epic
Mang AI co-pilot của SurfSense vào trình duyệt, cho phép users chat với AI, nhận insights về token, và lưu thông tin quan trọng ngay khi đang browse các trang crypto.
**Giá trị cho User:**
- **Chat với AI ngay trong browser** - Không cần chuyển tab, hỏi AI về bất kỳ token nào đang xem.
- **Tự động hiểu context** - AI biết bạn đang xem token gì trên DexScreener và đưa ra insights phù hợp.
- **Lưu thông tin nhanh** - Một cú click để lưu trang, token, insights vào knowledge base.
- **Đồng bộ mọi nơi** - Cài đặt và lịch sử chat được đồng bộ giữa extension và web dashboard.
---
## Các phụ thuộc kỹ thuật (Technical Dependencies)
Epic này phụ thuộc vào các API bên ngoài và backend services. Tất cả các integrations phải đáp ứng tiêu chí Định nghĩa hoàn thành (DoD) bên dưới.
### 1. DexScreener API Integration [FR-DAT-01]
**Mục đích:** Trích xuất dữ liệu token thời gian thực cho tính năng hỗ trợ AI nhận biết ngữ cảnh.
**API Endpoints:**
```typescript
// Public API (no auth required)
GET https://api.dexscreener.com/latest/dex/tokens/{tokenAddress}
GET https://api.dexscreener.com/latest/dex/pairs/{chainId}/{pairAddress}
GET https://api.dexscreener.com/latest/dex/search?q={query}
```
**Giới hạn tốc độ (Rate Limits):**
- **Free Tier:** 300 requests/phút
- **Xử lý:** Implement exponential backoff với tối đa 3 lần thử lại (retries)
- **Caching:** Cache token data trong 30 giây để giảm lượng API calls
**Xử lý lỗi (Error Handling):**
```typescript
// Retry logic
async function fetchDexScreenerData(tokenAddress: string, retries = 3) {
try {
const response = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${tokenAddress}`);
if (response.status === 429) {
// Rate limit exceeded
if (retries > 0) {
await sleep(2 ** (3 - retries) * 1000); // Exponential backoff
return fetchDexScreenerData(tokenAddress, retries - 1);
}
throw new Error('Rate limit exceeded. Please try again later.');
}
if (!response.ok) {
throw new Error(`DexScreener API error: ${response.status}`);
}
return await response.json();
} catch (error) {
// Show user-friendly error
showToast('Failed to fetch token data. Please try again.', 'error');
throw error;
}
}
```
**Định nghĩa hoàn thành (DoD):**
- [ ] Rate limiting được implement với exponential backoff
- [ ] Xử lý lỗi với thông báo thân thiện cho user
- [ ] Caching layer để giảm API calls
- [ ] Logic thử lại (tối đa 3 lần)
- [ ] Xử lý Timeout (tối đa 5 giây)
- [ ] Hỗ trợ chế độ Offline (hiện data đã cache)
- [ ] Unit tests cho các kịch bản lỗi
---
### 2. DefiLlama API Integration [FR-DAT-02]
**Mục đích:** TVL, protocol data, và các chỉ số DeFi để phân tích token toàn diện.
**API Endpoints:**
```typescript
// Public API (no auth required)
GET https://api.llama.fi/protocol/{protocol}
GET https://api.llama.fi/tvl/{protocol}
GET https://api.llama.fi/charts/{protocol}
```
**Giới hạn tốc độ (Rate Limits):**
- **Free Tier:** Không giới hạn (nhưng khuyến nghị tối đa 60 requests/phút)
- **Xử lý:** Implement rate limiting ở phía client
- **Caching:** Cache protocol data trong 5 phút
**Error Handling:**
```typescript
async function fetchDefiLlamaData(protocol: string) {
try {
const response = await fetch(`https://api.llama.fi/protocol/${protocol}`, {
signal: AbortSignal.timeout(5000), // 5 second timeout
});
if (!response.ok) {
throw new Error(`DefiLlama API error: ${response.status}`);
}
return await response.json();
} catch (error) {
if (error.name === 'TimeoutError') {
showToast('Request timed out. Please try again.', 'error');
} else {
showToast('Failed to fetch protocol data.', 'error');
}
throw error;
}
}
```
**Định nghĩa hoàn thành (DoD):**
- [ ] Client-side rate limiting (tối đa 60 req/phút)
- [ ] Xử lý lỗi với timeout (5 giây)
- [ ] Caching layer (5 phút TTL)
- [ ] Logic thử lại cho các lỗi tạm thời (transient errors)
- [ ] Hỗ trợ chế độ Offline
- [ ] Unit tests cho các kịch bản lỗi
---
### 3. Backend APIs
**Authentication:**
```typescript
GET /auth/google // OAuth URL
POST /auth/callback // OAuth callback
POST /auth/login // Email/password login
POST /auth/refresh // Refresh JWT
POST /auth/logout // Invalidate token
GET /auth/me // Get current user
```
**Settings:**
```typescript
GET /api/settings // Get user settings (model, search space, connectors)
PUT /api/settings // Update settings
```
**Chat:**
```typescript
GET /api/chat/messages // Get chat history
POST /api/chat/messages // Send message (streaming response)
POST /api/chat/save // Save chat to backend
```
**Capture:**
```typescript
POST /api/capture // Capture page content
GET /api/captures // List captured pages
```
**Định nghĩa hoàn thành (DoD):**
- [ ] Tất cả endpoints được document trong API spec
- [ ] Yêu cầu JWT authentication cho các protected endpoints
- [ ] Phản hồi lỗi tuân theo format chuẩn:
```json
{
"error": "Error message",
"code": "ERROR_CODE",
"details": {}
}
```
- [ ] Rate limiting trên backend (100 req/phút mỗi user)
- [ ] CORS được cấu hình cho extension origin
- [ ] Unit tests cho tất cả endpoints
---
### 4. Chrome APIs
**Required Permissions:**
```json
{
"permissions": [
"sidePanel",
"storage",
"tabs",
"identity",
"activeTab"
],
"host_permissions": [
"https://dexscreener.com/*",
"https://api.dexscreener.com/*",
"https://api.llama.fi/*"
]
}
```
**Chrome Identity API:**
```typescript
chrome.identity.launchWebAuthFlow({
url: `${BACKEND_URL}/auth/google`,
interactive: true,
}, (redirectUrl) => {
// Handle OAuth callback
});
```
**Chrome Storage API:**
```typescript
// Plasmo Storage wrapper
import { Storage } from "@plasmohq/storage";
const storage = new Storage();
await storage.set("auth_token", encryptedJWT);
const token = await storage.get("auth_token");
```
**Định nghĩa hoàn thành (DoD):**
- [ ] Manifest permissions được cấu hình
- [ ] Host permissions cho tất cả external APIs
- [ ] Storage encryption cho dữ liệu nhạy cảm
- [ ] Xử lý lỗi khi permission bị từ chối
- [ ] Unit tests cho các interactions với Chrome API
---
## User Stories
### Story 1.0: Hệ thống Xác thực (Authentication System)
**[FR-EXT-00]** ⚠️ **P0 BLOCKER**
**Là một** SurfSense user,
**Tôi muốn** đăng nhập vào extension với tài khoản SurfSense của tôi,
**Để** extension có thể đồng bộ settings, lịch sử chat, và truy cập backend APIs.
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 1.0.1: User Login Flow
**Given** user chưa đăng nhập vào extension
**When** user click nút "Login" trong side panel header
**Then** Chrome Identity API popup mở ra với các tùy chọn OAuth (Google, Email/Password)
**And** user chọn Google OAuth
**And** user hoàn tất quy trình OAuth
**Then** extension nhận JWT token từ backend
**And** extension chuyển hướng (redirects) về side panel
**And** avatar/email của user hiển thị trong header
**Kịch bản lỗi (Error Scenario):**
**Given** user đang trong quy trình OAuth
**When** OAuth thất bại (user hủy hoặc lỗi mạng)
**Then** extension hiển thị error toast "Login failed. Please try again."
**And** user vẫn ở trạng thái chưa xác thực (unauthenticated state)
---
#### AC 1.0.2: Quản lý JWT Token
**Given** backend trả về JWT token (hết hạn sau 7 ngày)
**When** extension nhận được token
**Then** extension lưu encrypted JWT trong Plasmo Storage
**And** thời gian hết hạn của token được lưu
**Auto-Refresh:**
**Given** JWT token còn < 1 ngày hết hạn
**When** extension kiểm tra token expiry (mỗi giờ)
**Then** extension gọi API `/auth/refresh`
**And** backend trả về JWT token mới
**And** extension cập nhật token đã lưu
**Logout:**
**Given** user click "Logout" trong settings dropdown
**When** hành động logout được kích hoạt
**Then** extension xóa JWT khỏi Plasmo Storage
**And** extension gọi API `/auth/logout`
**And** user chuyển hướng về màn hình welcome
---
#### AC 1.0.3: Authenticated API Requests
**Given** user đã đăng nhập (JWT đã lưu)
**When** extension thực hiện API request (ví dụ: `/chat/messages`)
**Then** request bao gồm header `Authorization: Bearer {JWT}`
**And** backend xác thực chữ ký JWT
**And** request thành công với status 200
**Expired Token:**
**Given** JWT token đã hết hạn
**When** extension thực hiện API request
**Then** backend trả về lỗi 401 Unauthorized
**And** extension cố gắng auto-refresh
**And** nếu refresh thành công, thử lại request ban đầu
**And** nếu refresh thất bại, chuyển hướng user đến trang login
---
#### AC 1.0.4: Xử lý Offline
**Given** user đã đăng nhập trước đó
**And** user mất kết nối internet
**When** extension cố gắng kết nối backend
**Then** extension hiển thị chỉ báo "Offline" trong header
**And** extension cache trạng thái auth gần nhất
**And** hành động của user (ví dụ: tin nhắn chat) được đưa vào hàng đợi (queued)
**Khi có mạng trở lại (Back Online):**
**Given** user đang offline với các hành động trong hàng đợi
**When** kết nối internet được khôi phục
**Then** extension đồng bộ các hành động trong hàng đợi với backend
**And** chỉ báo "Offline" biến mất
**And** user thấy toast thành công "Synced {N} actions"
**Triển khai kỹ thuật:**
```typescript
// Use Chrome Identity API for OAuth
chrome.identity.launchWebAuthFlow({
url: `${BACKEND_URL}/auth/google`,
interactive: true,
}, (redirectUrl) => {
// Extract JWT from redirect URL
const jwt = new URL(redirectUrl).searchParams.get('token');
// Store encrypted JWT
await storage.set('auth_token', encrypt(jwt));
});
// Auto-refresh token
setInterval(async () => {
const token = await storage.get('auth_token');
const decoded = decodeJWT(token);
if (isExpiringSoon(decoded.exp, 1 * 24 * 60 * 60)) {
const newToken = await refreshToken(token);
await storage.set('auth_token', encrypt(newToken));
}
}, 60 * 60 * 1000); // Check every hour
// Include JWT in all API requests
const api = {
async request(endpoint: string, options: RequestInit = {}) {
const token = await storage.get('auth_token');
return fetch(`${BACKEND_URL}${endpoint}`, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${decrypt(token)}`,
},
});
},
};
```
**Cân nhắc bảo mật (Security Considerations):**
- Không bao giờ lưu API keys trong extension code (hiển thị cho users)
- Mã hóa JWT trong Plasmo Storage
- Sử dụng HTTPS cho tất cả API calls
- Triển khai CSRF protection
- Validate chữ ký JWT trên backend
**Backend APIs Needed:**
```typescript
GET /auth/google // OAuth URL
POST /auth/callback // OAuth callback
POST /auth/login // Email/password login
POST /auth/refresh // Refresh JWT
POST /auth/logout // Invalidate token
GET /auth/me // Get current user
```
**Files:**
- `lib/auth/chrome-identity.ts` (new) - Chrome Identity API wrapper
- `lib/auth/jwt-manager.ts` (new) - JWT storage, refresh, validation
- `lib/auth/api-client.ts` (new) - Authenticated API client
- `sidepanel/auth/LoginButton.tsx` (new) - Login UI
- `sidepanel/auth/UserProfile.tsx` (new) - User avatar/menu
---
### Story 1.1: Kiến trúc Side Panel (Side Panel Architecture)
**[FR-EXT-01]**
**Là một** crypto trader,
**Tôi muốn** mở AI assistant dưới dạng side panel (không phải popup nhỏ),
**Để** tôi có thể chat với AI trong khi vẫn xem được DexScreener chart.
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 1.1.1: Mở Side Panel khi Click Icon
**Given** user đã cài đặt extension
**When** user click icon extension trong Chrome toolbar
**Then** side panel mở ra bên phải màn hình
**And** chiều rộng của side panel là 400px (mặc định)
**And** side panel không che khuất nội dung chính
---
#### AC 1.1.2: Thay đổi kích thước Side Panel (Resizable)
**Given** side panel đang mở
**When** user kéo cạnh trái của panel
**Then** chiều rộng panel thay đổi
**And** chiều rộng tối thiểu là 300px
**And** chiều rộng tối đa là 600px
**And** tùy chọn kích thước (resize preference) được lưu trong Plasmo Storage
---
#### AC 1.1.3: Side Panel Tồn tại qua các Tab
**Given** side panel đang mở trên tab A
**When** user chuyển sang tab B
**Then** side panel vẫn hiển thị trên tab B
**And** nội dung panel reload với context của tab B (nếu có)
**Edge Case:**
**Given** user đóng side panel trên tab A
**When** user chuyển sang tab B
**Then** side panel vẫn đóng trên tab B
---
#### AC 1.1.4: Manifest Permissions
**Given** extension được build
**When** developer kiểm tra `manifest.json`
**Then** `sidePanel` permission có trong manifest
**And** `openPanelOnActionClick: true` được thiết lập trong background script
**Ghi chú kỹ thuật (Technical Notes):**
```typescript
// background/index.ts
chrome.sidePanel
.setPanelBehavior({ openPanelOnActionClick: true })
.catch((error) => console.error("Failed to set side panel behavior:", error));
```
**Files:**
- `surfsense_browser_extension/sidepanel.tsx`
- `surfsense_browser_extension/package.json` (thêm sidePanel permission) ✅
---
### Story 1.2: Tích hợp Giao diện AI Chat (AI Chat Interface Integration)
**[FR-EXT-02, FR-INT-01]** ⭐ **AI MOAT**
**Là một** crypto trader,
**Tôi muốn** chat với AI trong extension giống như trên web dashboard,
**Để** tôi có trải nghiệm nhất quán và đầy đủ tính năng.
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 1.2.1: Tích hợp Giao diện Chat
**Given** user đã đăng nhập và mở side panel
**When** user gõ tin nhắn "Is BULLA token safe?" và nhấn Enter
**Then** tin nhắn hiển thị trong khung chat với avatar user
**And** phản hồi của AI bắt đầu streaming
**And** `@assistant-ui/react` Thread component renders chính xác
---
#### AC 1.2.2: Phản hồi Streaming
**Given** user đã gửi tin nhắn
**When** AI bắt đầu phản hồi
**Then** text phản hồi hiển thị từng từ (streaming)
**And** hiển thị các bước suy nghĩ (thinking steps visualization) (nếu có)
**And** user có thể cuộn trong khi AI đang phản hồi
**And** tự động cuộn xuống dưới cùng khi có nội dung mới
**Kịch bản lỗi (Error Scenario):**
**Given** kết nối streaming bị ngắt
**When** lỗi mạng xảy ra
**Then** extension hiển thị thông báo lỗi "Connection lost. Retrying..."
**And** extension cố gắng kết nối lại (tối đa 3 lần thử lại)
---
#### AC 1.2.3: Rendering Tool UI
**Given** AI response bao gồm tool outputs
**When** AI sử dụng tool `display_image`
**Then** component `DisplayImageToolUI` render hình ảnh
**And** hình ảnh có caption và metadata
**Link Preview:**
**Given** AI response bao gồm tool `link_preview`
**When** tool output renders
**Then** `LinkPreviewToolUI` hiển thị tiêu đề, mô tả, thumbnail
**Scraping:**
**Given** AI sử dụng tool `scrape_webpage`
**When** quá trình scraping hoàn tất
**Then** `ScrapeWebpageToolUI` hiển thị nội dung đã trích xuất
**And** user có thể mở rộng/thu gọn nội dung
---
#### AC 1.2.4: Lưu trữ Lịch sử Chat
**Given** user đã chat với AI
**When** user đóng extension
**And** user mở lại extension
**Then** lịch sử chat vẫn hiển thị (được load từ Plasmo Storage)
**And** user có thể cuộn lên xem tin nhắn cũ
**Đồng bộ Backend (Backend Sync):**
**Given** user đã đăng nhập
**When** tin nhắn chat được gửi
**Then** tin nhắn được đồng bộ với backend API (`POST /chat/messages`)
**And** lịch sử chat có thể truy cập từ web dashboard
---
#### AC 1.2.5: Dịch Truy vấn Ngôn ngữ Tự nhiên (Natural Language Query Translation) ⭐ [FR-INT-01]
**Given** user đang xem DexScreener
**When** user gõ "Show me trending Solana memes with >$10k liquidity"
**Then** AI dịch truy vấn thành DexScreener API filters:
```json
{
"chain": "solana",
"category": "meme",
"minLiquidity": 10000,
"sort": "trending"
}
```
**And** AI giải thích: "I'm searching for meme tokens on Solana with liquidity above $10k, sorted by trending volume."
**And** AI thực hiện tìm kiếm và trả về kết quả
**Truy vấn phức tạp (Complex Query):**
**Given** user hỏi "Find tokens launched in last 24h with >50% price increase"
**When** AI xử lý truy vấn
**Then** AI dịch thành:
```json
{
"minAge": 0,
"maxAge": 86400,
"minPriceChange24h": 50
}
```
**And** AI trả về kết quả đã lọc kèm lời giải thích
**Ví dụ Placeholder:**
**Given** user focus vào ô chat input
**When** input đang trống
**Then** placeholder hiển thị các ví dụ xoay vòng:
- "Show me new Solana tokens with high volume"
- "Find tokens with locked liquidity >90%"
- "What are the top trending meme coins today?"
**Component Reuse:**
```typescript
// From frontend
import { Thread } from "@/components/assistant-ui/thread";
import { DisplayImageToolUI } from "@/components/tool-ui/display-image";
import { LinkPreviewToolUI } from "@/components/tool-ui/link-preview";
import { ScrapeWebpageToolUI } from "@/components/tool-ui/scrape-webpage";
```
**Files:**
- `sidepanel/chat/ChatInterface.tsx`
- `sidepanel/chat/ChatMessages.tsx`
- `sidepanel/chat/ChatInput.tsx`
- `sidepanel/chat/ChatHeader.tsx`
---
### Story 1.3: Phát hiện Ngữ cảnh Trang (Page Context Detection)
**[FR-EXT-03]**
**Là một** crypto trader đang xem DexScreener,
**Tôi muốn** AI tự động hiểu tôi đang xem token nào,
**Để** tôi không cần copy/paste địa chỉ token mỗi lần.
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 1.3.1: Phát hiện Loại Trang (Page Type Detection)
**Given** user điều hướng đến trang DexScreener
**When** content script chạy
**Then** loại trang (page type) được phát hiện là `dexscreener`
**And** logic trích xuất token được kích hoạt
**Các trang khác:**
**Given** user điều hướng đến CoinGecko
**When** content script chạy
**Then** loại trang được phát hiện là `coingecko`
**Given** user điều hướng đến Twitter/X
**Then** loại trang được phát hiện là `twitter`
**Given** user điều hướng đến trang không xác định
**Then** loại trang được phát hiện là `generic`
---
#### AC 1.3.2: Trích xuất Dữ liệu Token (DexScreener)
**Given** user đang xem trang token: `dexscreener.com/solana/ABC123`
**When** content script trích xuất dữ liệu
**Then** các dữ liệu sau được trích xuất:
- Token address: `ABC123`
- Chain: `solana`
- Price: `$0.0001234`
- 24h Volume: `$10,234`
- Liquidity: `$5,123`
- Pair info: `BULLA/SOL`
**And** dữ liệu được gửi đến side panel qua `chrome.runtime.sendMessage`
---
#### AC 1.3.3: Context Injection vào Chat
**Given** dữ liệu token đã được trích xuất
**When** user mở chat
**Then** AI nhận được context: "You are viewing BULLA/SOL token on Solana. Address: ABC123. Current price: $0.0001234..."
**And** user có thể hỏi "Is this safe?" mà không cần chỉ định token
**Cập nhật Context:**
**Given** user điều hướng đến token khác
**When** dữ liệu token mới được trích xuất
**Then** chat context tự động cập nhật
**And** AI nhận biết token mới trong các tin nhắn tiếp theo
**Triển khai kỹ thuật:**
```typescript
// content.ts
function detectPageType(): PageType {
const hostname = window.location.hostname;
if (hostname.includes('dexscreener.com')) return 'dexscreener';
if (hostname.includes('coingecko.com')) return 'coingecko';
if (hostname.includes('twitter.com') || hostname.includes('x.com')) return 'twitter';
return 'generic';
}
function extractDexScreenerData(): TokenData {
// Extract from URL: /solana/address
// Or from page DOM
}
```
**Files:**
- `content.ts`
- `sidepanel/context/PageContextProvider.tsx`
---
### Story 1.4: Tích hợp Thông minh với DexScreener
**[FR-EXT-04]**
**Là một** crypto trader trên DexScreener,
**Tôi muốn** thấy thẻ thông tin token (token info card) ở đầu side panel,
**Để** tôi có thể nhanh chóng kiểm tra độ an toàn hoặc xem các holders.
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 1.4.1: Hiển thị Thẻ Thông tin Token
**Given** user điều hướng đến trang token DexScreener
**When** side panel mở ra
**Then** Token Info Card hiển thị ở đầu panel
**And** thẻ hiển thị:
- Token symbol/name: "BULLA/SOL"
- Current price: "$0.0001"
- 24h change: "+15%" (xanh nếu dương, đỏ nếu âm)
- Volume 24h: "$10K"
- Liquidity: "$5K"
---
#### AC 1.4.2: Các nút Thao tác Nhanh (Quick Action Buttons)
**Given** Token Info Card đang hiển thị
**When** user click nút "Is this token safe?"
**Then** chat input được điền sẵn "Is BULLA/SOL safe?"
**And** AI nhận đầy đủ token context
**And** AI thực hiện phân tích an toàn
**Top Holders:**
**Given** user click nút "Show top holders"
**When** hành động kích hoạt
**Then** chat được điền sẵn "Show top holders for BULLA/SOL"
**And** AI truy vấn dữ liệu blockchain
**Dự đoán giá (Price Prediction):**
**Given** user click nút "Price prediction"
**Then** chat được điền sẵn "Predict price for BULLA/SOL"
**And** AI thực hiện phân tích kỹ thuật
---
#### AC 1.4.3: Tự động Giải quyết Context (Auto-Context Resolution)
**Given** user gõ "Is this token safe?" (không chỉ định token)
**When** tin nhắn được gửi
**Then** AI giải quyết "this token" = token hiện tại trên DexScreener
**And** AI thực hiện phân tích trên token chính xác
**UI Design:**
```
┌─────────────────────────────┐
│ 🪙 BULLA/SOL │
│ $0.0001 📈 +15% │
│ Vol: $10K | Liq: $5K │
│ [Safety Check] [Holders] │
└─────────────────────────────┘
```
**Files:**
- `sidepanel/dexscreener/TokenInfoCard.tsx`
- `sidepanel/chat/ChatInterface.tsx` (integrate card) ✅
---
### Story 1.5: Lưu nhanh trang (Quick Capture)
**[FR-EXT-05]**
**Là một** crypto trader,
**Tôi muốn** lưu trang hiện tại vào không gian tìm kiếm (search space),
**Để** tôi có thể tham khảo lại sau.
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 1.5.1: Nút Quick Capture
**Given** side panel đang mở
**When** user cuộn trong panel
**Then** nút "📸 Save Current Page" vẫn hiển thị (sticky footer)
**And** nút không che khuất nội dung chat
---
#### AC 1.5.2: Quy trình Lưu Trang
**Given** user đang xem trang token DexScreener
**When** user click nút "📸 Save Current Page"
**Then** extension capture nội dung trang (HTML, metadata, screenshot)
**And** nội dung được lưu vào search space đã chọn của user
**And** thông báo toast hiển thị "Page saved successfully"
**And** trang đã lưu có thể truy cập từ web dashboard
**Kịch bản lỗi (Error Scenario):**
**Given** user chưa đăng nhập
**When** user click nút capture
**Then** extension hiển thị "Please login to save pages"
**And** login modal mở ra
---
#### AC 1.5.3: Tái sử dụng Chức năng Capture
**Given** web dashboard có API capture hiện có
**When** extension gọi capture
**Then** extension tái sử dụng endpoint `/api/capture`
**And** cùng một logic backend xử lý capture
**And** không có implementation trùng lặp
**Files:**
- `sidepanel/chat/QuickCapture.tsx`
---
### Story 1.6: Đồng bộ Cài đặt (Settings Sync) với Frontend
**[FR-EXT-06]**
**Là một** SurfSense user,
**Tôi muốn** extension sử dụng cùng model và search space như web dashboard,
**Để** tôi không phải cấu hình lại.
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 1.6.1: Hiển thị Dropdown Cài đặt
**Given** user đã đăng nhập
**When** user click icon ⚙️ trong header
**Then** settings dropdown mở ra
**And** dropdown hiển thị:
- Current model: "GPT-4 Turbo" (chỉ xem, bị mờ)
- Current search space: "Crypto Research" (chỉ xem, bị mờ)
- Links đến web dashboard:
- "🔗 Manage Connectors"
- "💬 View All Chats"
- "⚙️ Full Settings"
- Nút "🚪 Logout"
---
#### AC 1.6.2: Đồng bộ Cài đặt khi Đăng nhập
**Given** user hoàn tất đăng nhập
**When** nhận được JWT token
**Then** extension gọi `GET /api/settings`
**And** backend trả về:
```json
{
"model": "gpt-4-turbo",
"searchSpace": "crypto-research",
"connectors": ["dexscreener", "helius"]
}
```
**And** settings được lưu trong Plasmo Storage
**And** settings hiển thị trong dropdown
---
#### AC 1.6.3: Tự động cập nhật Cài đặt
**Given** user thay đổi model trên web dashboard
**When** extension phát hiện thay đổi (qua polling hoặc webhook)
**Then** extension lấy settings đã cập nhật
**And** dropdown phản ánh model mới
**And** các cuộc chat tiếp theo sử dụng model mới
**Polling:**
**Given** extension đang hoạt động
**When** mỗi 5 phút
**Then** extension polls `GET /api/settings`

View file

@ -1,302 +0,0 @@
# Epic 1: Extension Core Infrastructure
**Status:** ✅ COMPLETED
**Phase:** Phase 1
**Duration:** 2 weeks
**Priority:** P0 (Critical)
---
## Epic Overview
Xây dựng nền tảng cơ bản cho Chrome Extension với Side Panel architecture, tích hợp AI chat interface từ frontend, và context detection cho các trang crypto.
**Business Value:**
- Cho phép users chat với AI ngay trong browser
- Tự động detect và extract thông tin token từ DexScreener
- Tái sử dụng tối đa frontend components (giảm development time)
- Foundation cho tất cả features sau này
---
## User Stories
### Story 1.1: Side Panel Architecture
**[FR-EXT-01]**
**Là một** crypto trader,
**Tôi muốn** mở AI assistant dưới dạng side panel (không phải popup nhỏ),
**Để** tôi có thể chat với AI trong khi vẫn xem được DexScreener chart.
**Acceptance Criteria:**
- [ ] Extension icon click → Mở side panel bên phải màn hình
- [ ] Side panel width: 400px (default), resizable 300-600px
- [ ] Side panel không che khuất nội dung chính
- [ ] Side panel persist khi switch tabs
- [ ] Manifest có permission `sidePanel`
**Technical Notes:**
```typescript
// background/index.ts
chrome.sidePanel
.setPanelBehavior({ openPanelOnActionClick: true })
.catch((error) => console.error("Failed to set side panel behavior:", error));
```
**Files:**
- `surfsense_browser_extension/sidepanel.tsx`
- `surfsense_browser_extension/package.json` (add sidePanel permission) ✅
---
### Story 1.2: AI Chat Interface Integration
**[FR-EXT-02]**
**Là một** crypto trader,
**Tôi muốn** chat với AI trong extension giống như trên web dashboard,
**Để** tôi có trải nghiệm nhất quán và đầy đủ tính năng.
**Acceptance Criteria:**
- [ ] Tích hợp `@assistant-ui/react` Thread component
- [ ] Streaming responses hoạt động
- [ ] Thinking steps visualization hiển thị
- [ ] Tool UIs render đúng (images, links, scraping)
- [ ] Attachment handling (upload files/images)
- [ ] Chat history lưu vào Plasmo Storage
- [ ] Chat history sync với backend API
**Component Reuse:**
```typescript
// From frontend
import { Thread } from "@/components/assistant-ui/thread";
import { DisplayImageToolUI } from "@/components/tool-ui/display-image";
import { LinkPreviewToolUI } from "@/components/tool-ui/link-preview";
import { ScrapeWebpageToolUI } from "@/components/tool-ui/scrape-webpage";
```
**Files:**
- `sidepanel/chat/ChatInterface.tsx`
- `sidepanel/chat/ChatMessages.tsx`
- `sidepanel/chat/ChatInput.tsx`
- `sidepanel/chat/ChatHeader.tsx`
---
### Story 1.3: Page Context Detection
**[FR-EXT-03]**
**Là một** crypto trader đang xem DexScreener,
**Tôi muốn** AI tự động hiểu tôi đang xem token nào,
**Để** tôi không cần copy/paste token address mỗi lần.
**Acceptance Criteria:**
- [ ] Content script detect page type:
- DexScreener → Extract token data
- CoinGecko → Extract coin info
- Twitter/X → Extract crypto discussions
- Generic → Basic page info
- [ ] Token data extracted:
- Token address
- Chain (Solana, Ethereum, Base)
- Price, volume, liquidity
- Pair info
- [ ] Context injected vào chat: "You are viewing $TOKEN on Solana..."
- [ ] Context updates khi user navigate to different token
**Technical Implementation:**
```typescript
// content.ts
function detectPageType(): PageType {
const hostname = window.location.hostname;
if (hostname.includes('dexscreener.com')) return 'dexscreener';
if (hostname.includes('coingecko.com')) return 'coingecko';
if (hostname.includes('twitter.com') || hostname.includes('x.com')) return 'twitter';
return 'generic';
}
function extractDexScreenerData(): TokenData {
// Extract from URL: /solana/address
// Or from page DOM
}
```
**Files:**
- `content.ts`
- `sidepanel/context/PageContextProvider.tsx`
---
### Story 1.4: DexScreener Smart Integration
**[FR-EXT-04]**
**Là một** crypto trader trên DexScreener,
**Tôi muốn** thấy token info card ở top của side panel,
**Để** tôi có thể nhanh chóng check safety hoặc xem holders.
**Acceptance Criteria:**
- [ ] Token Info Card hiển thị khi detect DexScreener page
- [ ] Card shows:
- Token symbol/name
- Current price
- 24h change (%)
- Volume 24h
- Liquidity
- [ ] Quick action buttons:
- "Is this token safe?" → Trigger safety check
- "Show top holders" → Query blockchain
- "Price prediction" → AI analysis
- [ ] Buttons trigger chat with pre-filled context
- [ ] Auto-context: "this token" = token đang xem
**UI Design:**
```
┌─────────────────────────────┐
│ 🪙 BULLA/SOL │
│ $0.0001 📈 +15% │
│ Vol: $10K | Liq: $5K │
│ [Safety Check] [Holders] │
└─────────────────────────────┘
```
**Files:**
- `sidepanel/dexscreener/TokenInfoCard.tsx`
- `sidepanel/chat/ChatInterface.tsx` (integrate card) ✅
---
### Story 1.5: Quick Capture
**[FR-EXT-05]**
**Là một** crypto trader,
**Tôi muốn** save current page vào search space,
**Để** tôi có thể reference lại sau.
**Acceptance Criteria:**
- [ ] "📸 Save Current Page" button ở bottom của side panel
- [ ] Button sticky (luôn visible)
- [ ] Click → Capture page content
- [ ] Save vào selected search space
- [ ] Toast notification: "Page saved successfully"
- [ ] Reuse existing capture functionality
**Files:**
- `sidepanel/chat/QuickCapture.tsx`
---
### Story 1.6: Settings Sync với Frontend
**[FR-EXT-06]**
**Là một** SurfSense user,
**Tôi muốn** extension sử dụng cùng model và search space như web dashboard,
**Để** tôi không phải config lại.
**Acceptance Criteria:**
- [ ] Settings dropdown trong extension header
- [ ] Dropdown shows:
- Current model (read-only)
- Current search space (read-only)
- Links to frontend management
- [ ] Links:
- "Manage Connectors" → Open frontend /settings/connectors
- "View All Chats" → Open frontend /chats
- "Full Settings" → Open frontend /settings
- [ ] State sync:
- Extension reads from backend API
- Model selection synced
- Search space synced
- Enabled connectors synced (read-only)
- Chat history bidirectional sync
**API Endpoints Needed:**
```typescript
GET /api/user/settings
POST /api/user/settings
GET /api/models/available
GET /api/search-spaces
GET /api/connectors/enabled
```
**Plasmo Storage Structure:**
```typescript
interface ExtensionStorage {
settings: {
selectedModel: string;
searchSpaceId: string;
apiKey: string;
};
cachedSettings: UserSettings;
lastSync: number;
}
```
**Files:**
- `sidepanel/chat/ChatHeader.tsx` (add settings dropdown)
- `lib/api/settings-sync.ts` (new)
---
## Technical Dependencies
### Frontend Components to Reuse
- `@assistant-ui/react` Thread
- Tool UIs (images, links, scraping)
- Thinking steps visualization
- Chat utilities
### Backend APIs Needed
- `/api/user/settings` - Get/update user settings
- `/api/models/available` - List available models
- `/api/search-spaces` - List search spaces
- `/api/connectors/enabled` - List enabled connectors
- `/api/chat/stream` - Chat streaming (existing)
### Chrome APIs Used
- `chrome.sidePanel` - Side panel management
- `chrome.storage` - Plasmo Storage
- `chrome.tabs` - Tab management
- `chrome.runtime` - Messaging
---
## Testing Strategy
### Unit Tests
- [ ] PageContextProvider state management
- [ ] Token data extraction from DexScreener
- [ ] Settings sync logic
### Integration Tests
- [ ] Side panel opens on icon click
- [ ] Chat streaming works
- [ ] Context detection works on DexScreener
- [ ] Token card displays correctly
- [ ] Quick capture saves page
### Manual Testing
- [ ] Test on DexScreener.com
- [ ] Test on CoinGecko
- [ ] Test on Twitter
- [ ] Test settings sync with frontend
- [ ] Test chat history persistence
---
## Definition of Done
- [ ] All 6 stories completed
- [ ] All acceptance criteria met
- [ ] Unit tests passing
- [ ] Integration tests passing
- [ ] Manual testing completed
- [ ] Code reviewed
- [ ] Documentation updated
- [ ] Deployed to staging
---
## Notes
**Phase 1 Status:** ✅ COMPLETED (as of 2026-02-01)
**Next Epic:** Epic 2 - Smart Monitoring & Alerts (Phase 2)

View file

@ -1,57 +1,159 @@
# Epic 2: Smart Monitoring & Alerts
# Epic 2: Smart Monitoring & Alerts (Giám sát & Cảnh báo Thông minh)
**Status:** 📋 PLANNED
**Phase:** Phase 2
**Duration:** 2 weeks
**Priority:** P0 (Critical - Risk Protection)
**Trạng thái:** 📋 ĐÃ LÊN KẾ HOẠCH (PLANNED)
**Giai đoạn:** Phase 2
**Thời gian:** 2 tuần
**Mức độ ưu tiên:** P0 (Nghiêm trọng - Risk Protection)
---
## Epic Overview
## Tổng quan Epic
Xây dựng hệ thống monitoring và alerts thông minh để bảo vệ users khỏi rủi ro và giúp họ không bỏ lỡ cơ hội. Tập trung vào **risk protection** (rug pull detection) và **opportunity alerts** (whale activity, price movements).
**Business Value:**
- **Risk Protection:** Giúp users tránh mất tiền vào rug pulls
- **Opportunity Alerts:** Không bỏ lỡ whale movements và price spikes
- **Always-On Monitoring:** Background monitoring ngay cả khi browser đóng
- **Competitive Advantage:** Proactive alerts vs passive dashboards (DexScreener/DexTools)
**Giá trị kinh doanh (Business Value):**
- **Risk Protection (Bảo vệ rủi ro):** Giúp users tránh mất tiền vào rug pulls.
- **Opportunity Alerts (Cảnh báo cơ hội):** Không bỏ lỡ whale movements và price spikes.
- **Always-On Monitoring:** Giám sát ngầm (Background monitoring) ngay cả khi browser đóng.
- **Lợi thế cạnh tranh:** Proactive alerts (Chủ động cảnh báo) so với passive dashboards (DexScreener/DexTools).
**Key Differentiator:** AI-driven anomaly detection, không chỉ là threshold alerts.
**Điểm khác biệt chính:** AI-driven anomaly detection (Phát hiện bất thường bằng AI), không chỉ là threshold alerts.
---
## User Stories
### Story 2.1: Real-time Price Alerts
### Story 2.1: Cảnh báo Giá Thời gian thực (Real-time Price Alerts)
**[FR-EXT-07]**
**Là một** crypto trader,
**Tôi muốn** set price alerts cho tokens trong watchlist,
**Để** tôi được notify khi price hit target mà không cần stare vào chart cả ngày.
**Tôi muốn** đặt cảnh báo giá cho tokens trong watchlist,
**Để** tôi được thông báo (notify) khi giá chạm target mà không cần nhìn chằm chằm vào biểu đồ cả ngày.
**Acceptance Criteria:**
- [ ] Watchlist management trong side panel
- Add token to watchlist (from DexScreener page)
- Remove token from watchlist
- View all watchlist tokens
- Edit token alerts
- [ ] Alert types:
- Price above threshold (e.g., > $0.001)
- Price below threshold (e.g., < $0.0005)
- Price change % (e.g., +20% in 1h)
- Volume spike (e.g., 3x average volume)
- Liquidity change (e.g., -50% liquidity)
- [ ] Browser notifications:
- Work even when tab closed
- Show token symbol, price, change %
- Click notification → Open DexScreener page
- [ ] Sound alerts (optional):
- Enable/disable per alert
- Different sounds for different alert types
- [ ] Alert history:
- View past alerts
- Mark as read/unread
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 2.1.1: Quản lý Watchlist
**Given** user đang xem token trên DexScreener
**When** user click nút "Add to Watchlist" trong Token Info Card
**Then** token được thêm vào watchlist
**And** watchlist badge hiển thị "5 tokens"
**And** toast notification "Added BULLA/SOL to watchlist"
**Remove from Watchlist:**
**Given** token đang trong watchlist
**When** user click nút "Remove"
**Then** confirmation modal xuất hiện "Remove BULLA/SOL from watchlist?"
**And** user xác nhận (confirms)
**Then** token bị xóa khỏi watchlist
**And** tất cả alerts liên quan bị xóa
**View Watchlist:**
**Given** user có 5 tokens trong watchlist
**When** user mở Watchlist panel
**Then** tất cả 5 tokens hiển thị với:
- Token symbol và chain
- Giá hiện tại (Current price)
- Thay đổi 24h (24h change %)
- Số lượng active alerts
- Nút [Edit] [Remove]
---
#### AC 2.1.2: Cấu hình Loại Alert
**Given** user có token trong watchlist
**When** user click nút "Add Alert"
**Then** modal cấu hình alert mở ra với các tùy chọn:
**Price Above Threshold (Giá trên ngưỡng):**
**Given** user chọn "Price Above"
**When** user nhập ngưỡng "$0.00015"
**Then** alert được tạo
**And** background worker kiểm tra giá mỗi 1 phút
**When** giá vượt quá $0.00015
**Then** browser notification hiển thị "🚀 BULLA/SOL hit $0.00016 (+6.7%)"
**Price Below Threshold (Giá dưới ngưỡng):**
**Given** user chọn "Price Below"
**When** user nhập ngưỡng "$0.0005"
**Then** alert kích hoạt khi giá giảm xuống dưới ngưỡng
**Price Change % (Biến động giá %):**
**Given** user chọn "Price Change %"
**When** user nhập "+20% in 1h"
**Then** alert kích hoạt khi giá tăng 20% trong vòng 1 giờ
**Volume Spike (Khối lượng tăng đột biến):**
**Given** user chọn "Volume Spike"
**When** user nhập "3x average volume"
**Then** alert kích hoạt khi volume vượt quá 3 lần trung bình 24h
**Liquidity Change (Thay đổi thanh khoản):**
**Given** user chọn "Liquidity Change"
**When** user nhập "-50% liquidity"
**Then** alert kích hoạt khi thanh khoản giảm 50% so với baseline
---
#### AC 2.1.3: Browser Notifications
**Given** user có active price alert
**When** điều kiện alert được đáp ứng
**Then** browser notification xuất hiện với:
- Token symbol: "BULLA/SOL"
- Current price: "$0.00016"
- Change %: "+6.7%"
- Alert type: "Price Above $0.00015"
**Hoạt động khi đóng Tab:**
**Given** user đã đóng tất cả browser tabs
**When** alert kích hoạt
**Then** notification vẫn xuất hiện (nhờ background service worker)
**Click Notification:**
**Given** user nhận thông báo
**When** user click vào thông báo
**Then** tab mới mở ra với trang DexScreener cho token đó
**And** side panel tự động mở với token context
---
#### AC 2.1.4: Cảnh báo Âm thanh (Sound Alerts)
**Given** user bật sound alerts
**When** alert kích hoạt
**Then** âm thanh phát ra dựa trên loại alert:
- Price Above: "ding.mp3" (âm thanh tích cực)
- Price Below: "alert.mp3" (âm thanh cảnh báo)
- Volume Spike: "chime.mp3" (âm thanh chú ý)
**Enable/Disable Per Alert:**
**Given** user có nhiều alerts
**When** user bật tắt âm thanh cho một alert cụ thể
**Then** chỉ alert đó mới phát âm thanh
**And** các alerts khác vẫn im lặng
---
#### AC 2.1.5: Lịch sử Alert (Alert History)
**Given** user có alerts đã kích hoạt
**When** user mở panel "Alert History"
**Then** danh sách hiển thị 100 alerts gần nhất với:
- Thời gian: "2 hours ago"
- Token: "BULLA/SOL"
- Alert type: "Price Above $0.00015"
- Triggered price: "$0.00016"
- Trạng thái Read/Unread
**Mark as Read:**
**Given** alert chưa đọc (unread)
**When** user click vào alert
**Then** alert được đánh dấu là đã đọc
**And** số lượng badge unread giảm đi
**Filter History:**
**Given** user có 100+ alerts
**When** user filter theo token "BULLA/SOL"
**Then** chỉ hiển thị alerts của BULLA
**When** user filter theo loại "Price Above"
**Then** chỉ hiển thị alerts giá trên ngưỡng
**UI Design:**
```
@ -70,7 +172,7 @@ Xây dựng hệ thống monitoring và alerts thông minh để bảo vệ user
└─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
interface PriceAlert {
id: string;
@ -108,35 +210,119 @@ GET /api/alerts/check // Returns triggered alerts
---
### Story 2.2: Whale Activity Tracker
### Story 2.2: Theo dõi Hoạt động Cá voi (Whale Activity Tracker)
**[FR-EXT-08]**
**Là một** crypto trader,
**Tôi muốn** được notify khi có whale buy/sell lớn,
**Để** tôi có thể follow smart money và tránh bị dumped.
**Tôi muốn** được thông báo khi có giao dịch mua/bán lớn (whale buy/sell),
**Để** tôi có thể theo chân dòng tiền thông minh (smart money) và tránh bị xả hàng (dumped).
**Acceptance Criteria:**
- [ ] Monitor large transactions:
- Configurable thresholds: $10K, $50K, $100K
- Detect buy vs sell
- Show transaction size in USD
- [ ] Wallet clustering detection:
- Identify same entity (multiple wallets)
- Show total holdings across wallets
- [ ] Smart money tracking:
- Track specific wallet addresses
- Alert on their activities
- Show their historical performance
- [ ] Transaction details:
- Wallet address
- Transaction hash
- Amount (tokens + USD)
- Time
- Link to explorer
- [ ] Notification:
- Browser notification for whale activity
- Show in side panel feed
- Filter by token (only watchlist or all)
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 2.2.1: Giám sát Giao dịch Lớn
**Given** user có token trong watchlist
**When** phát hiện giao dịch cá voi (whale transaction) (>$10K)
**Then** thông báo xuất hiện "🐋 $100K BUY detected for BULLA/SOL"
**And** chi tiết giao dịch hiển thị:
- Loại: BUY hoặc SELL
- Số lượng: "1B tokens ($100,000)"
- Ví: "0x1234...5678"
- Thời gian: "2 min ago"
**Configurable Thresholds (Ngưỡng có thể cấu hình):**
**Given** user mở cài đặt whale
**When** user chọn ngưỡng "$50K"
**Then** chỉ các giao dịch >$50K mới kích hoạt alerts
**And** các giao dịch nhỏ hơn bị bỏ qua
**Phát hiện Mua vs Bán:**
**Given** whale bán lượng token trị giá $100K
**When** giao dịch được phát hiện
**Then** thông báo hiển thị "🔴 SELL $100K BULLA/SOL"
**And** màu đỏ chỉ thị áp lực bán
---
#### AC 2.2.2: Phát hiện Gom nhóm Ví (Wallet Clustering Detection)
**Given** cùng một thực thể kiểm soát nhiều ví
**When** hệ thống phát hiện các ví liên quan
**Then** các ví được nhóm lại với nhau
**And** hiển thị tổng holdings trên tất cả các ví
**Ví dụ:**
**Given** ví A và B thuộc cùng một thực thể
**When** ví A mua 500M tokens
**And** ví B mua 300M tokens
**Then** hệ thống hiển thị "Entity holds 800M tokens across 2 wallets"
---
#### AC 2.2.3: Theo dõi Smart Money
**Given** user xác định được ví có lợi nhuận cao
**When** user click "Track This Wallet"
**Then** ví được thêm vào danh sách smart money
**And** tất cả giao dịch tương lai từ ví này sẽ kích hoạt alerts
**Hiệu suất Lịch sử:**
**Given** ví đang được theo dõi là smart money
**When** user xem chi tiết ví
**Then** hệ thống hiển thị:
- Tổng số giao dịch: 50
- Tỷ lệ thắng (Win rate): 75%
- Lợi nhuận trung bình: +120%
- Các giao dịch gần đây (10 giao dịch cuối)
**Cảnh báo Hoạt động:**
**Given** ví smart money thực hiện giao dịch
**When** giao dịch được phát hiện
**Then** thông báo ưu tiên "⚠️ Smart Money Alert: Wallet 0x1234 bought $50K PEPE"
**And** thông báo có mức ưu tiên cao hơn whale alerts thông thường
---
#### AC 2.2.4: Chi tiết Giao dịch
**Given** phát hiện giao dịch cá voi
**When** user click vào thông báo
**Then** modal chi tiết mở ra với:
- Địa chỉ ví: "0x1234...5678" (có thể copy)
- Transaction hash: "0xabcd...ef01" (có thể copy)
- Số lượng: "1B tokens ($100,000)"
- Thời gian: "2 min ago (14:30:15 UTC)"
- Link tới block explorer
- Nút [Track This Wallet]
**Link tới Explorer:**
**Given** user click "View on Explorer"
**When** link được click
**Then** tab mới mở ra với:
- Solana: Solscan.io
- Ethereum: Etherscan.io
- Base: BaseScan.org
---
#### AC 2.2.5: Feed Hoạt động Cá voi
**Given** phát hiện nhiều giao dịch cá voi
**When** user mở panel Whale Activity
**Then** feed hiển thị danh sách theo thời gian:
- Gần nhất ở trên cùng
- 50 giao dịch cuối cùng
- Gom nhóm theo token
- Lọc theo: Tất cả tokens / Chỉ Watchlist
**Tùy chọn Lọc:**
**Given** user có 100 whale transactions
**When** user lọc "Watchlist only"
**Then** chỉ hiển thị giao dịch của tokens trong watchlist
**When** user lọc "Smart Money only"
**Then** chỉ hiển thị giao dịch của ví được theo dõi
**Cập nhật Real-time:**
**Given** user đang mở panel Whale Activity
**When** phát hiện giao dịch cá voi mới
**Then** item mới xuất hiện ở đầu feed
**And** hiệu ứng trượt mượt mà (smooth animation)
**And** badge unread tăng lên
**UI Design:**
```
@ -157,7 +343,7 @@ GET /api/alerts/check // Returns triggered alerts
└─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
interface WhaleTransaction {
id: string;
@ -196,36 +382,145 @@ async function monitorWhaleActivity() {
---
### Story 2.3: Rug Pull Early Warning System
### Story 2.3: Hệ thống Cảnh báo Sớm Rug Pull (Rug Pull Early Warning System)
**[FR-EXT-09]**
**Là một** crypto trader,
**Tôi muốn** được cảnh báo sớm về rug pull risks,
**Để** tôi không mất tiền vào scam tokens.
**Tôi muốn** được cảnh báo sớm về rủi ro rug pull,
**Để** tôi không mất tiền vào các token lừa đảo (scam tokens).
**Acceptance Criteria:**
- [ ] Risk indicators monitored:
- LP removal (liquidity pulled)
- Mint authority changes (can mint more tokens)
- Suspicious holder patterns (top 10 holders > 80%)
- Contract ownership (not renounced)
- Honeypot detection (can't sell)
- [ ] Risk score calculation:
- 0-3: Low risk (green)
- 4-6: Medium risk (yellow)
- 7-10: High risk (red)
- [ ] Risk score display:
- Show on Token Info Card
- Update in real-time
- Explain each risk factor
- [ ] Recommendations:
- SAFE: "Low risk, proceed with caution"
- CAUTION: "Medium risk, do your own research"
- AVOID: "High risk, likely scam"
- [ ] Alerts:
- Notify when risk score increases
- Notify on LP removal
- Notify on mint authority changes
**Tiêu chí chấp nhận (Acceptance Criteria - BDD Format):**
#### AC 2.3.1: Giám sát Chỉ số Rủi ro (Risk Indicators Monitoring)
**Given** user đang xem token trên DexScreener
**When** hệ thống phân tích contract của token
**Then** các chỉ số rủi ro sau được kiểm tra:
**Phát hiện Rút thanh khoản (LP Removal Detection):**
**Given** token có liquidity pool
**When** LP tokens bị rút hoặc mở khóa (unlocked)
**Then** điểm rủi ro +3 điểm
**And** cảnh báo "🔴 LP REMOVED: BULLA/SOL - Potential rug pull!"
**Thay đổi Quyền Mint (Mint Authority Changes):**
**Given** token mint authority tồn tại
**When** mint authority chưa được từ bỏ (not renounced)
**Then** điểm rủi ro +2 điểm
**And** cảnh báo "🟡 Mint authority active - can create unlimited tokens"
**Mô hình Holder Đáng ngờ:**
**Given** token có phân bổ holder
**When** top 10 holders sở hữu >80% nguồn cung
**Then** điểm rủi ro +2 điểm
**And** cảnh báo "🟡 Centralized ownership - top 10 hold 85%"
**Quyền sở hữu Contract:**
**Given** token contract có chủ sở hữu (owner)
**When** ownership chưa được từ bỏ
**Then** điểm rủi ro +1 điểm
**And** cảnh báo "🟡 Contract owner can modify code"
**Phát hiện Honeypot:**
**Given** token contract được phân tích
**When** chức năng bán bị vô hiệu hóa hoặc hạn chế
**Then** điểm rủi ro +3 điểm
**And** cảnh báo nghiêm trọng "🔴 HONEYPOT DETECTED - Cannot sell!"
---
#### AC 2.3.2: Tính toán Điểm Rủi ro (Risk Score Calculation)
**Given** tất cả chỉ số rủi ro đã được phân tích
**When** hệ thống tính tổng điểm rủi ro
**Then** điểm số hiển thị như sau:
**Rủi ro Thấp (Low Risk - 0-3):**
**Given** điểm rủi ro = 2
**Then** badge hiển thị "✅ Low Risk (2/10)"
**And** màu xanh lá
**And** khuyến nghị "SAFE: Proceed with caution"
**Rủi ro Trung bình (Medium Risk - 4-6):**
**Given** điểm rủi ro = 5
**Then** badge hiển thị "⚠️ Medium Risk (5/10)"
**And** màu vàng
**And** khuyến nghị "CAUTION: Do your own research"
**Rủi ro Cao (High Risk - 7-10):**
**Given** điểm rủi ro = 8
**Then** badge hiển thị "🔴 High Risk (8/10)"
**And** màu đỏ
**And** khuyến nghị "AVOID: Likely scam"
---
#### AC 2.3.3: Hiển thị Điểm Rủi ro
**Given** token đã được phân tích
**When** user xem Token Info Card
**Then** điểm rủi ro hiển thị nổi bật:
- Risk badge ở trên cùng
- Các yếu tố rủi ro riêng lẻ được liệt kê
- Mỗi yếu tố với icon (🔴/🟡/🟢)
- Giải thích cho mỗi yếu tố
**Cập nhật Real-time:**
**Given** điểm rủi ro ban đầu là 3/10
**When** LP bị rút (rủi ro tăng lên 6/10)
**Then** risk badge cập nhật ngay lập tức
**And** màu thay đổi từ xanh -> vàng
**And** gửi thông báo
**Giải thích Yếu tố Rủi ro:**
**Given** user click vào risk badge
**When** modal chi tiết mở ra
**Then** giải thích từng yếu tố:
- "🔴 LP unlocked (High Risk): Liquidity can be removed anytime"
- "🟡 Top holder owns 40%: Centralized ownership risk"
- "🟢 Contract verified: Code is public and audited"
---
#### AC 2.3.4: Khuyến nghị (Recommendations)
**Given** điểm rủi ro đã tính toán
**When** hệ thống tạo khuyến nghị
**Then** thông điệp phù hợp hiển thị:
**SAFE (0-3):**
**Then** thông điệp "✅ Low risk, proceed with caution. Always DYOR."
**CAUTION (4-6):**
**Then** thông điệp "⚠️ Medium risk, do your own research. Some red flags detected."
**AVOID (7-10):**
**Then** thông điệp "🔴 High risk, likely scam. Strong evidence of rug pull potential."
---
#### AC 2.3.5: Cảnh báo Rủi ro (Risk Alerts)
**Given** user có token trong watchlist
**When** điểm rủi ro tăng lên
**Then** cảnh báo được kích hoạt
**Tăng Điểm Rủi ro:**
**Given** điểm rủi ro là 3/10
**When** rủi ro tăng lên 7/10
**Then** thông báo "⚠️ RISK ALERT: BULLA/SOL risk increased to 7/10 (High Risk)"
**Cảnh báo Rút LP:**
**Given** token có LP bị khóa
**When** LP bị rút
**Then** cảnh báo khẩn cấp "🚨 URGENT: LP REMOVED from BULLA/SOL - Exit immediately!"
**And** âm thanh cảnh báo phát ra
**And** thông báo tồn tại cho đến khi bị tắt (dismissed)
**Thay đổi Quyền Mint:**
**Given** mint authority đã được từ bỏ
**When** mint authority được kích hoạt lại
**Then** cảnh báo "⚠️ WARNING: Mint authority changed for BULLA/SOL"
**Phát hiện Honeypot:**
**Given** token có thể bán được
**When** honeypot bị phát hiện
**Then** cảnh báo nghiêm trọng "🔴 HONEYPOT: Cannot sell BULLA/SOL - Do not buy!"
**UI Design:**
```
@ -247,7 +542,7 @@ async function monitorWhaleActivity() {
└─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
interface RiskAssessment {
tokenAddress: string;
@ -266,50 +561,6 @@ interface RiskAssessment {
explanation: string;
timestamp: number;
}
async function assessRugPullRisk(tokenAddress: string, chain: string): Promise<RiskAssessment> {
// Check LP lock status
const lpLocked = await checkLPLock(tokenAddress, chain);
// Check mint authority
const mintAuthority = await checkMintAuthority(tokenAddress, chain);
// Check holder distribution
const holders = await getTopHolders(tokenAddress, chain);
const topHolderPercent = calculateTopHolderPercent(holders);
// Check contract verification
const contractVerified = await isContractVerified(tokenAddress, chain);
// Check honeypot
const isHoneypot = await checkHoneypot(tokenAddress, chain);
// Calculate risk score
const riskScore = calculateRiskScore({
lpLocked,
mintAuthority,
topHolderPercent,
contractVerified,
isHoneypot,
});
return {
tokenAddress,
chain,
riskScore,
riskLevel: getRiskLevel(riskScore),
indicators: {
lpLocked,
mintAuthority,
topHolderPercent,
contractVerified,
isHoneypot,
},
recommendation: getRecommendation(riskScore),
explanation: generateExplanation(riskScore, indicators),
timestamp: Date.now(),
};
}
```
**Data Sources:**
@ -355,20 +606,20 @@ GET /api/risk/assess
## Testing Strategy
### Unit Tests
- [ ] Risk score calculation
- [ ] Whale transaction detection
- [ ] Alert triggering logic
- [ ] Tính toán điểm rủi ro (Risk score calculation)
- [ ] Phát hiện giao dịch cá voi (Whale transaction detection)
- [ ] Logic kích hoạt cảnh báo (Alert triggering logic)
### Integration Tests
- [ ] Price alerts trigger correctly
- [ ] Whale activity notifications work
- [ ] Risk assessment updates in real-time
- [ ] Price alerts kích hoạt chính xác
- [ ] Thông báo hoạt động cá voi hoạt động
- [ ] Đánh giá rủi ro cập nhật realtime
### Manual Testing
- [ ] Add token to watchlist
- [ ] Set price alert and verify notification
- [ ] Monitor whale activity on live token
- [ ] Check rug pull warning on known scam token
- [ ] Thêm token vào watchlist
- [ ] Đặt price alert và xác minh thông báo
- [ ] Giám sát hoạt động cá voi trên live token
- [ ] Kiểm tra cảnh báo rug pull trên scam token đã biết
---
@ -385,8 +636,8 @@ GET /api/risk/assess
---
## Notes
## Ghi chú
**Priority Justification:** Risk protection (rug pull detection) is CRITICAL for user trust. Users will not use the product if they lose money to scams.
**Priority Justification:** Risk protection (rug pull detection) là QUAN TRỌNG (CRITICAL) cho niềm tin của user. Users sẽ không sử dụng sản phẩm nếu họ mất tiền vì scams.
**Next Epic:** Epic 3 - Trading Intelligence (Phase 3)

View file

@ -1,77 +1,77 @@
# Epic 3: Trading Intelligence
# Epic 3: Trading Intelligence (Trí tuệ Giao dịch)
**Status:** 📋 PLANNED
**Phase:** Phase 3
**Duration:** 2 weeks
**Priority:** P1 (High - Value Add)
**Trạng thái:** 📋 ĐÃ LÊN KẾ HOẠCH (PLANNED)
**Giai đoạn:** Phase 3
**Thời gian:** 2 tuần
**Mức độ ưu tiên:** P1 (Cao - Giá trị gia tăng)
---
## Epic Overview
## Tổng quan Epic
Cung cấp AI-powered trading insights để giúp users make better trading decisions. Tập trung vào **comprehensive analysis**, **entry/exit suggestions**, và **portfolio tracking**.
Cung cấp AI-powered trading insights để giúp users ra quyết định giao dịch tốt hơn (make better trading decisions). Tập trung vào **phân tích toàn diện (comprehensive analysis)**, **gợi ý điểm vào/ra (entry/exit suggestions)**, và **theo dõi danh mục đầu tư (portfolio tracking)**.
**Business Value:**
- **Better Decisions:** AI-generated insights giúp users trade smarter
- **Time Savings:** One-click analysis thay vì hours of research
- **Portfolio Management:** Track performance và optimize holdings
- **Competitive Advantage:** AI predictions vs static data (DexScreener/DexTools)
**Giá trị kinh doanh (Business Value):**
- **Quyết định tốt hơn:** AI-generated insights giúp users trade thông minh hơn.
- **Tiết kiệm thời gian:** Phân tích một cú click thay vì hàng giờ nghiên cứu.
- **Quản lý danh mục:** Theo dõi hiệu suất và tối ưu hóa holdings.
- **Lợi thế cạnh tranh:** Dự đoán AI so với dữ liệu tĩnh (DexScreener/DexTools).
**Key Differentiator:** AI-first analysis với natural language explanations.
**Điểm khác biệt chính:** Phân tích ưu tiên AI (AI-first analysis) với các giải thích bằng ngôn ngữ tự nhiên.
---
## User Stories
### Story 3.1: One-Click Token Analysis
### Story 3.1: Phân tích Token Một Cú Click (One-Click Token Analysis)
**[FR-EXT-10]**
**Là một** crypto trader,
**Tôi muốn** analyze token với một click,
**Để** tôi có comprehensive insights mà không cần research thủ công.
**Để** tôi có insights toàn diện mà không cần nghiên cứu thủ công.
**Acceptance Criteria:**
- [ ] "Analyze This Token" button trên Token Info Card
- [ ] Comprehensive analysis includes:
- **Contract Analysis:**
- Verified/unverified
- Renounced ownership
- Proxy contract detection
- Source code availability
- **Holder Distribution:**
- Top 10 holders percentage
- Holder count
- Whale concentration
- Distribution chart
- **Liquidity Analysis:**
- Total liquidity (USD)
- LP lock status & duration
- Liquidity history (7d, 30d)
- Liquidity/Market cap ratio
- **Trading Volume:**
- 24h volume
- Volume trend (increasing/decreasing)
- Volume/Liquidity ratio
- Unusual volume spikes
- **Price History:**
- All-time high/low
- 7d, 30d performance
- Price volatility
- Support/resistance levels
- **Social Sentiment:**
**Tiêu chí chấp nhận (Acceptance Criteria):**
- [ ] Nút "Analyze This Token" trên Thẻ Thông tin Token (Token Info Card)
- [ ] Phân tích toàn diện bao gồm:
- **Phân tích Hợp đồng (Contract Analysis):**
- Đã xác minh/chưa xác minh (Verified/unverified)
- Từ bỏ quyền sở hữu (Renounced ownership)
- Phát hiện Proxy contract
- Tính khả dụng của mã nguồn (Source code availability)
- **Phân bổ Holder (Holder Distribution):**
- Tỷ lệ Top 10 holders
- Số lượng Holder
- Độ tập trung của Whale
- Biểu đồ phân bổ
- **Phân tích Thanh khoản (Liquidity Analysis):**
- Tổng thanh khoản (USD)
- Trạng thái khóa LP & thời hạn
- Lịch sử thanh khoản (7 ngày, 30 ngày)
- Tỷ lệ Thanh khoản/Vốn hóa (Liquidity/Market cap ratio)
- **Khối lượng Giao dịch (Trading Volume):**
- Volume 24h
- Xu hướng Volume (tăng/giảm)
- Tỷ lệ Volume/Thanh khoản
- Các đợt tăng volume bất thường (Unusual volume spikes)
- **Lịch sử Giá (Price History):**
- Giá cao nhất/thấp nhất mọi thời đại (ATH/ATL)
- Hiệu suất 7 ngày, 30 ngày
- Biến động giá (Price volatility)
- Các mức Hỗ trợ/Kháng cự (Support/resistance levels)
- **Cảm xúc Xã hội (Social Sentiment):**
- Twitter mentions
- Telegram activity
- Reddit discussions
- Sentiment score (positive/negative/neutral)
- [ ] AI-Generated Summary:
- 2-3 sentence summary
- Key insights highlighted
- Risk assessment
- Trading recommendation
- [ ] Analysis caching:
- Cache for 5 minutes
- Show "Last updated" timestamp
- Refresh button
- Hoạt động Telegram
- Thảo luận Reddit
- Điểm cảm xúc (tích cực/tiêu cực/trung lập)
- [ ] Tóm tắt do AI tạo (AI-Generated Summary):
- Tóm tắt 2-3 câu
- Các insight chính được làm nổi bật
- Đánh giá rủi ro (Risk assessment)
- Khuyến nghị giao dịch (Trading recommendation)
- [ ] Caching phân tích:
- Cache trong 5 phút
- Hiển thị timestamp "Cập nhật lần cuối"
- Nút Refresh
**UI Design:**
```
@ -104,10 +104,10 @@ Cung cấp AI-powered trading insights để giúp users make better trading dec
│ │
│ [View Full Report] │
│ Last updated: 2 min ago │
└─────────────────────────────┘
107: └─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
interface TokenAnalysis {
tokenAddress: string;
@ -211,36 +211,36 @@ async function analyzeToken(tokenAddress: string, chain: string): Promise<TokenA
---
### Story 3.2: Smart Entry/Exit Suggestions
### Story 3.2: Gợi ý Điểm Vào/Ra Thông minh (Smart Entry/Exit Suggestions)
**[FR-EXT-11]**
**Là một** crypto trader,
**Tôi muốn** AI suggest entry/exit points,
**Để** tôi maximize profits và minimize losses.
**Tôi muốn** AI gợi ý các điểm entry/exit,
**Để** tôi tối đa hóa lợi nhuận và giảm thiểu rủi ro.
**Acceptance Criteria:**
- [ ] Technical analysis:
- Support/Resistance levels (3 levels each)
- Fibonacci retracement levels
- Volume profile analysis
- Moving averages (20, 50, 200)
- [ ] AI predictions:
- Predicted price targets (3 levels)
- Time horizon (1h, 4h, 24h)
- Confidence score per prediction
- [ ] Risk/Reward calculation:
- Suggested entry range
- Stop loss level
- Take profit levels (3 targets)
- Risk/Reward ratio
- [ ] Visual representation:
- Price chart with levels marked
- Entry/exit zones highlighted
- Risk/reward visualization
- [ ] Explanation:
- Why these levels?
- What signals support this?
- What could invalidate this?
**Tiêu chí chấp nhận (Acceptance Criteria):**
- [ ] Phân tích kỹ thuật (Technical analysis):
- Các mức Hỗ trợ/Kháng cự (3 levels each)
- Các mức Fibonacci retracement
- Phân tích Volume profile
- Đường trung bình động (Moving averages) (20, 50, 200)
- [ ] Dự đoán của AI (AI predictions):
- Mục tiêu giá dự kiến (Predicted price targets) (3 levels)
- Khung thời gian (1h, 4h, 24h)
- Điểm tin cậy (Confidence score) cho mỗi dự đoán
- [ ] Tính toán Rủi ro/Lợi nhuận (Risk/Reward):
- Vùng vào lệnh gợi ý (Suggested entry range)
- Mức cắt lỗ (Stop loss level)
- Các mức chốt lời (Take profit levels) (3 targets)
- Tỷ lệ Risk/Reward
- [ ] Trực quan hóa (Visual representation):
- Biểu đồ giá với các levels được đánh dấu
- Vùng entry/exit được làm nổi bật
- Trực quan hóa Risk/reward
- [ ] Giải thích (Explanation):
- Tại sao lại là các levels này?
- Tín hiệu nào hỗ trợ điều này?
- Điều gì có thể vô hiệu hóa dự đoán này?
**UI Design:**
```
@ -272,7 +272,7 @@ async function analyzeToken(tokenAddress: string, chain: string): Promise<TokenA
└─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
interface TradingSuggestion {
tokenAddress: string;
@ -320,40 +320,40 @@ interface TradingSuggestion {
---
### Story 3.3: Portfolio Tracker Integration
### Story 3.3: Tích hợp Theo dõi Portfolio (Portfolio Tracker Integration)
**[FR-EXT-12]**
**Là một** crypto trader,
**Tôi muốn** track portfolio trong extension,
**Để** tôi biết P&L real-time mà không cần mở nhiều tabs.
**Tôi muốn** theo dõi portfolio ngay trong extension,
**Để** tôi biết P&L realtime mà không cần mở nhiều tab.
**Acceptance Criteria:**
- [ ] Wallet connection:
- Support MetaMask, Phantom, Coinbase Wallet
- Multi-wallet support
- Auto-detect holdings
- [ ] Portfolio overview:
- Total value (USD)
- 24h P&L ($ and %)
**Tiêu chí chấp nhận (Acceptance Criteria):**
- [ ] Kết nối Ví (Wallet connection):
- Hỗ trợ MetaMask, Phantom, Coinbase Wallet
- Hỗ trợ Multi-wallet
- Tự động phát hiện holdings
- [ ] Tổng quan Portfolio:
- Tổng giá trị (USD)
- 24h P&L ($ %)
- All-time P&L
- Asset allocation chart
- [ ] Holdings list:
- Biểu đồ phân bổ tài sản
- [ ] Danh sách Holdings:
- Token symbol/name
- Amount held
- Current value
- 24h change
- P&L per token
- Entry price (if available)
- [ ] Performance analytics:
- Số lượng nắm giữ (Amount held)
- Giá trị hiện tại
- Thay đổi 24h
- P&L theo từng token
- Giá entry (nếu có sẵn)
- [ ] Phân tích Hiệu suất (Performance analytics):
- Best/worst performers
- Win rate
- Average hold time
- Total trades
- [ ] Quick actions:
- Tỷ lệ thắng (Win rate)
- Thời gian giữ trung bình (Average hold time)
- Tổng số giao dịch
- [ ] Thao tác nhanh (Quick actions):
- Analyze token
- Set price alert
- View on DexScreener
- Sell (link to DEX)
- Xem trên DexScreener
- Sell (link tới DEX)
**UI Design:**
```
@ -384,7 +384,7 @@ interface TradingSuggestion {
└─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
interface Portfolio {
wallets: {
@ -429,7 +429,7 @@ interface Portfolio {
---
## Technical Dependencies
## Các phụ thuộc kỹ thuật (Technical Dependencies)
### Backend APIs
```
@ -453,38 +453,38 @@ GET /api/portfolio/analytics
---
## Testing Strategy
## Chiến lược Kiểm thử (Testing Strategy)
### Unit Tests
- [ ] Token analysis calculation
- [ ] Trading suggestion algorithm
- [ ] Portfolio P&L calculation
- [ ] Tính toán phân tích Token
- [ ] Thuật toán gợi ý giao dịch
- [ ] Tính toán P&L Portfolio
### Integration Tests
- [ ] Wallet connection flow
- [ ] Portfolio data fetching
- [ ] Analysis generation
- [ ] Quy trình kết nối Wallet
- [ ] Fetch dữ liệu Portfolio
- [ ] Tạo phân tích (Analysis generation)
### Manual Testing
- [ ] Analyze live token
- [ ] Connect wallet and view portfolio
- [ ] Verify trading suggestions accuracy
- [ ] Phân tích một token trực tiếp (live token)
- [ ] Kết nối ví và xem portfolio
- [ ] Xác minh độ chính xác của các gợi ý giao dịch
---
## Definition of Done
## Định nghĩa hoàn thành (Definition of Done)
- [ ] All 3 stories completed
- [ ] All acceptance criteria met
- [ ] Unit tests passing
- [ ] Integration tests passing
- [ ] Manual testing completed
- [ ] Wallet integrations working
- [ ] Code reviewed
- [ ] Documentation updated
- [ ] Tất cả 3 user stories hoàn thành
- [ ] Tất cả tiêu chí chấp nhận (acceptance criteria) được đáp ứng
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing hoàn thành
- [ ] Tích hợp Wallet hoạt động
- [ ] Code được review
- [ ] Tài liệu được cập nhật
---
## Notes
## Ghi chú
**Next Epic:** Epic 4 - Content Creation & Productivity (Phase 4)

View file

@ -1,65 +1,65 @@
# Epic 4: Content Creation & Productivity
# Epic 4: Content Creation & Productivity (Tạo Nội dung & Hiệu suất)
**Status:** 📋 PLANNED
**Phase:** Phase 4
**Duration:** 2 weeks
**Priority:** P2 (Medium - Nice to Have)
**Trạng thái:** 📋 ĐÃ LÊN KẾ HOẠCH (PLANNED)
**Giai đoạn:** Phase 4
**Thời gian:** 2 tuần
**Mức độ ưu tiên:** P2 (Trung bình - Nên có (Nice to Have))
---
## Epic Overview
## Tổng quan Epic
Tạo tools giúp users create content (charts, threads) và improve productivity (quick actions, notifications, shortcuts). Tập trung vào **content creators****power users**.
Tạo tools giúp users tạo nội dung (biểu đồ, threads) và cải thiện hiệu suất (thao tác nhanh, thông báo, phím tắt). Tập trung vào **content creators****power users**.
**Business Value:**
- **Content Creators:** Tools để tạo Twitter threads, chart screenshots
- **Power Users:** Keyboard shortcuts, quick actions để work faster
- **Viral Marketing:** Users share content → Free marketing
- **User Retention:** Productivity features → Sticky product
**Giá trị kinh doanh (Business Value):**
- **Content Creators:** Công cụ để tạo Twitter threads, chụp ảnh biểu đồ (chart screenshots).
- **Power Users:** Phím tắt, thao tác nhanh để làm việc nhanh hơn.
- **Viral Marketing:** Users chia sẻ nội dung → Marketing miễn phí.
- **User Retention:** Các tính năng hiệu suất → Sản phẩm có độ kết dính cao (Sticky product).
**Key Differentiator:** AI-powered content generation vs manual tools.
**Điểm khác biệt chính:** Tạo nội dung bằng AI (AI-powered content generation) so với công cụ thủ công.
---
## User Stories
### Story 4.1: Chart Screenshot with Annotations
### Story 4.1: Chụp ảnh Biểu đồ có Chú thích (Chart Screenshot with Annotations)
**[FR-EXT-13]**
**Là một** crypto content creator,
**Tôi muốn** capture và annotate charts,
**Để** tôi có thể share insights trên Twitter/Telegram.
**Tôi muốn** chụp và chú thích biểu đồ (capture và annotate charts),
**Để** tôi có thể chia sẻ insights trên Twitter/Telegram.
**Acceptance Criteria:**
- [ ] One-click chart capture:
- Capture from DexScreener page
- Auto-detect chart area
- High-resolution screenshot
- [ ] Auto-add metadata:
**Tiêu chí chấp nhận (Acceptance Criteria):**
- [ ] Chụp biểu đồ một cú click (One-click chart capture):
- Capture từ trang DexScreener
- Tự động phát hiện vùng biểu đồ
- Screenshot độ phân giải cao
- [ ] Tự động thêm metadata (Auto-add metadata):
- Token symbol/name
- Current price
- 24h change
- Volume, liquidity
- Timestamp
- Watermark (optional)
- [ ] Drawing tools:
- Lines (trend lines, support/resistance)
- Arrows (direction indicators)
- Text labels
- Shapes (circles, rectangles)
- Giá hiện tại
- Thay đổi 24h
- Volume, thanh khoản
- Thời gian (Timestamp)
- Watermark (tùy chọn)
- [ ] Công cụ vẽ (Drawing tools):
- Đường (trend lines, support/resistance)
- Mũi tên (chỉ hướng)
- Nhãn văn bản (Text labels)
- Hình dạng (tròn, chữ nhật)
- Fibonacci retracement
- [ ] Template styles:
- Dark mode (default)
- [ ] Kiểu mẫu (Template styles):
- Dark mode (mặc định)
- Light mode
- Neon (crypto aesthetic)
- Custom colors
- [ ] Export options:
- Twitter format (1200x675)
- Telegram format (square)
- Instagram format (1080x1080)
- Custom size
- Copy to clipboard
- Save to file
- Màu tùy chỉnh
- [ ] Tùy chọn xuất (Export options):
- Định dạng Twitter (1200x675)
- Định dạng Telegram (vuông)
- Định dạng Instagram (1080x1080)
- Kích thước tùy chỉnh
- Copy o clipboard
- Lưu thành file
**UI Design:**
```
@ -86,7 +86,7 @@ Tạo tools giúp users create content (charts, threads) và improve productivit
└─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
interface ChartCapture {
screenshot: Blob;
@ -137,41 +137,41 @@ function addAnnotations(canvas: HTMLCanvasElement, annotations: Annotation[]) {
---
### Story 4.2: AI Thread Generator
### Story 4.2: AI tạo Thread Twitter (AI Thread Generator)
**[FR-EXT-14]**
**Là một** crypto content creator,
**Tôi muốn** AI generate Twitter threads,
**Để** tôi có thể share insights nhanh chóng.
**Tôi muốn** AI tạo Twitter threads,
**Để** tôi có thể chia sẻ insights nhanh chóng.
**Acceptance Criteria:**
- [ ] Input:
- Token address (auto-filled if on DexScreener)
- Thread topic (optional)
- Thread length (5-10 tweets)
- Tone (bullish/neutral/bearish)
- [ ] AI generation:
- Analyze token data
- Generate thread structure
- Include key stats
- Add charts/screenshots
- Optimize for engagement
- [ ] Thread structure:
- Tweet 1: Hook (attention grabber)
- Tweets 2-4: Analysis (data, insights)
- Tweets 5-7: Implications (what it means)
- Tweet 8-9: Conclusion (summary, CTA)
- Tweet 10: Disclaimer (optional)
- [ ] Editing:
- Edit each tweet
- Reorder tweets
- Add/remove tweets
- Preview thread
- [ ] Export:
- Copy all tweets
- Copy individual tweet
- Tweet directly (Twitter API)
- Save as draft
**Tiêu chí chấp nhận (Acceptance Criteria):**
- [ ] Đầu vào (Input):
- Token address (tự động điền nếu đang trên DexScreener)
- Chủ đề Thread (tùy chọn)
- Độ dài Thread (5-10 tweets)
- Giọng điệu (Tone) (bullish/neutral/bearish)
- [ ] AI tạo nội dung (AI generation):
- Phân tích dữ liệu token
- Tạo cấu trúc thread
- Bao gồm các thống kê chính
- Thêm biểu đồ/screenshots
- Tối ưu hóa cho tương tác (engagement)
- [ ] Cấu trúc Thread:
- Tweet 1: Hook (thu hút sự chú ý)
- Tweets 2-4: Phân tích (dữ liệu, insights)
- Tweets 5-7: Hàm ý/Tác động (Implications - điều này có nghĩa là gì)
- Tweet 8-9: Kết luận (tóm tắt, CTA)
- Tweet 10: Tuyên bố miễn trừ trách nhiệm (Disclaimer - tùy chọn)
- [ ] Chỉnh sửa (Editing):
- Chỉnh sửa từng tweet
- Sắp xếp lại thứ tự tweets
- Thêm/xóa tweets
- Xem trước thread
- [ ] Xuất (Export):
- Copy tất cả tweets
- Copy từng tweet
- Tweet trực tiếp (Twitter API)
- Lưu nháp (Save as draft)
**UI Design:**
```
@ -194,13 +194,15 @@ function addAnnotations(canvas: HTMLCanvasElement, annotations: Annotation[]) {
│ │ 2/ Contract analysis: │ │
│ │ ✅ Verified ✅ Renounced│ │
│ │ [Edit] │ │
│ ├─────────────────────────┤ │
│ │ ... │ │
│ └─────────────────────────┘ │
│ │
│ [Copy All] [Tweet Now] │
└─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
interface ThreadRequest {
tokenAddress: string;
@ -247,65 +249,65 @@ async function generateThread(request: ThreadRequest): Promise<GeneratedThread>
---
### Story 4.3: Quick Actions & Productivity
### Story 4.3: Thao tác Nhanh & Hiệu suất (Quick Actions & Productivity)
**[FR-EXT-15, FR-EXT-16, FR-EXT-17]**
**Là một** power user,
**Tôi muốn** quick actions và shortcuts,
**Để** tôi có thể work faster.
**Tôi muốn** có các thao tác nhanh và phím tắt,
**Để** tôi có thể làm việc nhanh hơn.
**Acceptance Criteria:**
**Tiêu chí chấp nhận (Acceptance Criteria):**
#### Quick Actions Context Menu (FR-EXT-15)
- [ ] Right-click on token address → Context menu
- [ ] Menu items:
- "Add to Watchlist"
- "Analyze Token"
- "Check Safety"
- "Copy Address"
- "View on Explorer"
- "View on DexScreener"
- [ ] Works on any webpage (not just DexScreener)
- [ ] Auto-detect token address format
#### Menu ngữ cảnh Thao tác nhanh (Quick Actions Context Menu) (FR-EXT-15)
- [ ] Chuột phải vào địa chỉ token → Menu ngữ cảnh
- [ ] Các mục Menu:
- "Add to Watchlist" (Thêm vào Watchlist)
- "Analyze Token" (Phân tích Token)
- "Check Safety" (Kiểm tra an toàn)
- "Copy Address" (Sao chép địa chỉ)
- "View on Explorer" (Xem trên Explorer)
- "View on DexScreener" (Xem trên DexScreener)
- [ ] Hoạt động trên bất kỳ trang web nào (không chỉ DexScreener)
- [ ] Tự động phát hiện định dạng địa chỉ token
#### Smart Notifications (FR-EXT-16)
- [ ] Notification priority levels:
- High: Rug pull warnings, whale dumps
- Medium: Price alerts, volume spikes
- Low: General updates
- [ ] Quiet hours:
- Set sleep schedule (e.g., 11pm - 7am)
- No notifications during quiet hours
- Emergency alerts only (rug pulls)
- [ ] Grouped notifications:
- Group by token
- Group by type
- Collapse similar notifications
- [ ] Smart batching:
- 5+ alerts → 1 summary notification
- "5 price alerts triggered"
- Click to expand
- [ ] Per-token settings:
- Enable/disable notifications
- Set priority level
- Custom quiet hours
#### Thông báo Thông minh (Smart Notifications) (FR-EXT-16)
- [ ] Các mức ưu tiên thông báo:
- Cao (High): Cảnh báo Rug pull, whale xả hàng
- Trung bình (Medium): Cảnh báo giá, khối lượng tăng đột biến
- Thấp (Low): Các cập nhật chung
- [ ] Giờ yên tĩnh (Quiet hours):
- Đặt lịch ngủ (ví dụ: 11pm - 7am)
- Không có thông báo trong giờ yên tĩnh
- Chỉ cảnh báo khẩn cấp (rug pulls)
- [ ] Gom nhóm thông báo (Grouped notifications):
- Gom theo token
- Gom theo loại
- Thu gọn các thông báo tương tự
- [ ] Gom nhóm thông minh (Smart batching):
- 5+ cảnh báo → 1 thông báo tóm tắt
- "5 cảnh báo giá đã được kích hoạt"
- Click để mở rộng
- [ ] Cài đặt theo từng token (Per-token settings):
- Bật/tắt thông báo
- Đặt mức ưu tiên
- Giờ yên tĩnh tùy chỉnh
#### Keyboard Shortcuts (FR-EXT-17)
- [ ] Global shortcuts:
- `Cmd+Shift+S`Open side panel
- `Cmd+Shift+H`Hide side panel
- `Cmd+Shift+N`New chat
- [ ] Context shortcuts (when on DexScreener):
- `Cmd+Shift+A`Analyze current token
- `Cmd+Shift+W`Add to watchlist
- `Cmd+Shift+C` → Capture chart
- `Cmd+Shift+T`Generate thread
- [ ] Portfolio shortcuts:
- `Cmd+Shift+P`Open portfolio
- `Cmd+Shift+R`Refresh portfolio
- [ ] Customizable shortcuts:
- User can remap shortcuts
- No conflicts with browser shortcuts
#### Phím tắt Bàn phím (Keyboard Shortcuts) (FR-EXT-17)
- [ ] Phím tắt toàn cục (Global shortcuts):
- `Cmd+Shift+S`Mở side panel
- `Cmd+Shift+H`Ẩn side panel
- `Cmd+Shift+N`Chat mới
- [ ] Phím tắt ngữ cảnh (khi trên DexScreener):
- `Cmd+Shift+A`Phân tích token hiện tại
- `Cmd+Shift+W`Thêm vào watchlist
- `Cmd+Shift+C` → Chụp biểu đồ
- `Cmd+Shift+T`Tạo thread
- [ ] Phím tắt Portfolio:
- `Cmd+Shift+P`Mở portfolio
- `Cmd+Shift+R`Làm mới portfolio
- [ ] Phím tắt tùy chỉnh:
- User có thể remap phím tắt
- Không xung đột với phím tắt trình duyệt
**UI Design - Settings:**
```
@ -330,7 +332,7 @@ async function generateThread(request: ThreadRequest): Promise<GeneratedThread>
└─────────────────────────────┘
```
**Technical Implementation:**
**Triển khai kỹ thuật:**
```typescript
// Context menu
chrome.contextMenus.create({
@ -395,57 +397,57 @@ function shouldShowNotification(notification: Notification, settings: Notificati
---
## Technical Dependencies
## Các phụ thuộc kỹ thuật (Technical Dependencies)
### Chrome APIs
- `chrome.contextMenus` - Context menu
- `chrome.commands` - Keyboard shortcuts
- `chrome.notifications` - Notifications
- `chrome.alarms` - Quiet hours
- `chrome.commands` - Phím tắt bàn phím
- `chrome.notifications` - Thông báo
- `chrome.alarms` - Giờ yên tĩnh
### External Libraries
- `html2canvas` - Chart capture
- `fabric.js` - Drawing tools (optional)
- `html2canvas` - Chụp biểu đồ
- `fabric.js` - Công cụ vẽ (tùy chọn)
---
## Testing Strategy
## Chiến lược Kiểm thử (Testing Strategy)
### Unit Tests
- [ ] Token address detection
- [ ] Notification priority logic
- [ ] Quiet hours calculation
- [ ] Logic phát hiện địa chỉ token
- [ ] Logic ưu tiên thông báo
- [ ] Tính toán giờ yên tĩnh
### Integration Tests
- [ ] Chart capture works
- [ ] Thread generation works
- [ ] Context menu appears
- [ ] Shortcuts trigger actions
- [ ] Chụp biểu đồ hoạt động
- [ ] Tạo thread hoạt động
- [ ] Menu ngữ cảnh xuất hiện
- [ ] Phím tắt kích hoạt hành động
### Manual Testing
- [ ] Capture chart and annotate
- [ ] Generate thread for live token
- [ ] Test all keyboard shortcuts
- [ ] Verify quiet hours work
- [ ] Chụp và chú thích biểu đồ
- [ ] Tạo thread cho token live
- [ ] Test tất cả các phím tắt
- [ ] Xác minh giờ yên tĩnh hoạt động
---
## Definition of Done
## Định nghĩa hoàn thành (Definition of Done)
- [ ] All 3 stories completed
- [ ] All acceptance criteria met
- [ ] Unit tests passing
- [ ] Integration tests passing
- [ ] Manual testing completed
- [ ] Code reviewed
- [ ] Documentation updated
- [ ] Tất cả 3 user stories hoàn thành
- [ ] Tất cả tiêu chí chấp nhận được đáp ứng
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing hoàn thành
- [ ] Code được review
- [ ] Tài liệu được cập nhật
---
## Notes
## Ghi chú
**Target Users:** Content creators và power users.
**Marketing Opportunity:** User-generated content (threads, charts) → Free viral marketing.
**Cơ hội Marketing:** User-generated content (threads, charts) → Viral marketing miễn phí.
**All Epics Complete!** 🎉
**Tất cả Epics Đã Hoàn Thành!** 🎉