Files
binance-alpha-farm-agent/README.md

473 lines
11 KiB
Markdown

# Binance Alpha Farm Agent
Automated trading agent for Binance Alpha Farm with Task-Step architecture.
## 🏗️ System Architecture
### Core Components
- **AppState**: Centralized state management with observer pattern
- **TaskRunner**: Task execution engine
- **StateWatchers**: Observers for state changes
- **BAF API**: Server communication module
- **BINANCE**: Binance page detection and navigation
## 📋 Task-Step System
### Task Types
```javascript
TASK_TYPES = {
LOGIN: 'login',
GET_ORDER_HISTORY: 'get_order_history',
GET_BALANCE: 'get_balance',
SWAP: 'swap',
NO_TASK: 'no_task'
}
```
### Step Types
```javascript
STEP_TYPES = {
// Login task steps
NAVIGATE_TO_LOGIN: 'navigate_to_login',
SELECT_QR_CODE: 'select_qr_code',
SEND_TO_SERVER: 'send_to_server',
WAIT_FOR_LOGIN: 'wait_for_login',
REPORT_RESULT: 'report_result',
// Order history task steps
NAVIGATE_TO_ORDER_HISTORY: 'navigate_to_order_history',
EXTRACT_ORDER_DATA: 'extract_order_data',
SEND_ORDER_DATA: 'send_order_data',
// Balance task steps
NAVIGATE_TO_BALANCE: 'navigate_to_balance',
EXTRACT_BALANCE_DATA: 'extract_balance_data',
SEND_BALANCE_DATA: 'send_balance_data',
// Swap task steps
NAVIGATE_TO_SWAP: 'navigate_to_swap',
FILL_SWAP_FORM: 'fill_swap_form',
CONFIRM_SWAP: 'confirm_swap',
WAIT_FOR_SWAP: 'wait_for_swap',
// Common steps
WAIT: 'wait',
ERROR_HANDLING: 'error_handling'
}
```
## 🤖 Bot Status Flow
### Status Types
```javascript
BOT_STATUS = {
READY_FOR_NEW_TASKS: 'ready-for-new-tasks',
PAUSE_AUTOMATION: 'pause-automation',
PERFORMING_TASKS: 'performing-tasks'
}
```
### Main Flow
```
┌─────────────────┐
│ Initialize │
└─────────┬───────┘
┌─────────────────┐
│ Check Bot Status│
└─────────┬───────┘
┌─────────────────┐ ┌─────────────────┐
│ Ready for Tasks │────▶│ Ask Server │
└─────────┬───────┘ │ for Tasks │
│ └─────────┬───────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ Sleep │ │ No Task Found │
│ (Interval) │◀────│ │
└─────────┬───────┘ └─────────────────┘
┌─────────────────┐ ┌─────────────────┐
│ Check Bot Status│────▶│ Task Received │
└─────────┬───────┘ └─────────┬───────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ Ready for Tasks │ │ Perform Task │
└─────────────────┘ └─────────┬───────┘
┌─────────────────┐
│ Task Complete │
└─────────┬───────┘
┌─────────────────┐
│ Return to Ready │
└─────────────────┘
```
### Status Transitions
1. **READY_FOR_NEW_TASKS**
- Poll server for new tasks
- Sleep for `task_poll_interval` if no tasks
- Transition to `PERFORMING_TASKS` when task received
2. **PAUSE_AUTOMATION**
- Stop all automation
- No polling or task execution
- Manual intervention required
3. **PERFORMING_TASKS**
- Execute current task step by step
- Update task data during execution
- Transition back to `READY_FOR_NEW_TASKS` when complete
## 📊 Task Data Examples
### Login Task
```javascript
{
type: TASK_TYPES.LOGIN,
id: "task_123",
data: {
method: LOGIN_METHOD.QR_CODE, // 'qr_code' | 'password' | 'email'
credentials: {
email: 'user@example.com', // For password method
password: 'password123' // For password method
},
timeout: 300000, // 5 minutes timeout
retry_count: 3
},
steps: [
STEP_TYPES.NAVIGATE_TO_LOGIN,
STEP_TYPES.SELECT_QR_CODE,
STEP_TYPES.SEND_TO_SERVER,
STEP_TYPES.WAIT_FOR_LOGIN,
STEP_TYPES.REPORT_RESULT
]
}
```
### Get Order History Task
```javascript
{
type: TASK_TYPES.GET_ORDER_HISTORY,
id: "task_124",
data: {
limit: 100,
offset: 0,
date_range: {
start_date: '2024-01-01',
end_date: '2024-12-31'
},
order_types: [
ORDER_TYPE.SWAP,
ORDER_TYPE.LIMIT,
ORDER_TYPE.MARKET
],
status: [
ORDER_STATUS.COMPLETED,
ORDER_STATUS.PENDING,
ORDER_STATUS.CANCELLED
]
},
steps: [
STEP_TYPES.NAVIGATE_TO_ORDER_HISTORY,
STEP_TYPES.EXTRACT_ORDER_DATA,
STEP_TYPES.SEND_ORDER_DATA
]
}
```
### Get Balance Task
```javascript
{
type: TASK_TYPES.GET_BALANCE,
id: "task_125",
data: {
currencies: ['USDT', 'BTC', 'ETH'], // null for all currencies
include_zero: false,
include_locked: true,
format: BALANCE_FORMAT.JSON // 'json' | 'csv'
},
steps: [
STEP_TYPES.NAVIGATE_TO_BALANCE,
STEP_TYPES.EXTRACT_BALANCE_DATA,
STEP_TYPES.SEND_BALANCE_DATA
]
}
```
### Swap Task
```javascript
{
type: TASK_TYPES.SWAP,
id: "task_126",
data: {
from_token: 'USDT',
to_token: 'BTC',
amount: 100,
slippage: 0.5, // percentage
gas_fee: GAS_FEE_TYPE.AUTO, // 'auto' | 'fast' | 'slow' | number
deadline: 300, // seconds
auto_confirm: true
},
steps: [
STEP_TYPES.NAVIGATE_TO_SWAP,
STEP_TYPES.FILL_SWAP_FORM,
STEP_TYPES.CONFIRM_SWAP,
STEP_TYPES.WAIT_FOR_SWAP
]
}
```
## 🔧 Enums & Constants
### Login Method
```javascript
LOGIN_METHOD = {
QR_CODE: 'qr_code',
PASSWORD: 'password',
EMAIL: 'email'
}
```
### Order Type
```javascript
ORDER_TYPE = {
SWAP: 'swap',
LIMIT: 'limit',
MARKET: 'market'
}
```
### Order Status
```javascript
ORDER_STATUS = {
COMPLETED: 'completed',
PENDING: 'pending',
CANCELLED: 'cancelled'
}
```
### Balance Format
```javascript
BALANCE_FORMAT = {
JSON: 'json',
CSV: 'csv'
}
```
### Gas Fee Type
```javascript
GAS_FEE_TYPE = {
AUTO: 'auto',
FAST: 'fast',
SLOW: 'slow'
}
```
## 🎯 Page Detection
### Supported Pages
```javascript
BINANCE_PAGES = {
LOGIN: 'login',
ALPHA_SWAP: 'alpha-swap',
ALPHA_ORDER_HISTORY: 'alpha-order-history',
UNKNOWN: 'unknown'
}
```
### Page URLs
- **Login**: `https://accounts.binance.com/login`
- **Alpha Swap**: `https://www.binance.com/alpha/bsc/`
- **Alpha Order History**: `https://www.binance.com/en/my/orders/alpha/orderhistory`
## 🔄 State Management
### AppState Structure
```javascript
{
// Server configuration
server_mode: 'prod',
server: { label: '🌐 Prod', url: 'https://baf.thuanle.me' },
// Page state
current_page: 'alpha-swap',
is_logged_in: true,
// Bot status
bot_status: BOT_STATUS.READY_FOR_NEW_TASKS,
// Task state
current_task: { type: 'login', id: 'task_123', ... },
task_data: { method: 'qr_code', timeout: 300000, ... },
current_step: 'navigate_to_login',
step_data: { attempts: 0, start_time: 1234567890 },
// UI state
is_loading: false,
error_message: null
}
```
### Observer Pattern
State changes trigger observers:
- **server_mode** → Save to storage, reload page
- **bot_status** → Save to storage, start/stop task polling
- **current_page** → Continue current step if task active
- **is_logged_in** → Continue current step if task active
## 🛠️ Helper Functions
### TaskRunner Helpers
```javascript
// Validate enum values
TaskRunner.validateEnum(value, enumObj, defaultValue)
// Validate and merge task data
TaskRunner.validateTaskData(taskType, taskData)
// Get current task data
TaskRunner.getCurrentTaskData()
// Update task data during execution
TaskRunner.updateTaskData(newData)
// Check current task type
TaskRunner.isCurrentTaskType(TASK_TYPES.LOGIN)
// Get current task type
TaskRunner.getCurrentTaskType()
```
### State Helpers
```javascript
// Get current state
APP_STATE.getData()
// Update state (triggers observers)
APP_STATE.update({ bot_status: BOT_STATUS.PERFORMING_TASKS })
// Subscribe to state changes
APP_STATE.subscribe('bot_status', callback)
// Unsubscribe from state changes
APP_STATE.unsubscribe('bot_status', callback)
```
## 🎮 Menu Commands
### Available Commands
1. **Server**: Switch between local/prod servers
2. **Token**: Configure Bearer token for API access
3. **Bot Status**: Cycle through bot statuses (ready/pause/performing)
4. **Get Tasks**: Manually check for new tasks
### Usage
```javascript
// Access via Tampermonkey menu
// Right-click extension icon → Binance Alpha Farm Agent
```
## 📡 API Endpoints
### Server Communication
```javascript
// Ping server with status
BAF.ping(status)
// Get new task
BAF.getTasks()
// Submit task result
BAF.submitTaskResult(taskId, result)
```
### Status Payload
```javascript
{
logged_in: true,
current_page: 'alpha-swap',
bot_status: 'ready-for-new-tasks',
current_task: 'login',
task_data: { method: 'qr_code', ... },
current_step: 'navigate_to_login',
has_current_task: true
}
```
## 🔧 Configuration
### CONFIG Object
```javascript
CONFIG = {
heartbeat_interval: 10000, // 10 seconds
task_poll_interval: 10000, // 10 seconds
is_debug: true,
servers: {
local: { label: '🏠 Local', url: 'http://localhost:3000' },
prod: { label: '🌐 Prod', url: 'https://baf.thuanle.me' }
}
}
```
## 🚀 Getting Started
1. Install Tampermonkey browser extension
2. Install the user script
3. Configure server token via menu
4. Set bot status to "ready-for-new-tasks"
5. Bot will automatically start polling for tasks
## 📝 Development Notes
### Adding New Task Types
1. Add to `TASK_TYPES` enum
2. Define task data structure in `TASK_DATA_EXAMPLES`
3. Add validation in `validateTaskData()`
4. Implement execution method in `TaskRunner`
5. Define steps in `STEP_TYPES`
### Adding New Steps
1. Add to `STEP_TYPES` enum
2. Implement step logic in task execution
3. Update step data during execution
4. Handle step transitions
### Error Handling
- Invalid enum values fallback to defaults
- Task execution errors return bot to ready state
- Network errors trigger retry after interval
- Page navigation errors handled by observers