Initial commit
This commit is contained in:
271
docs/MEV_BOT.md
Normal file
271
docs/MEV_BOT.md
Normal file
@@ -0,0 +1,271 @@
|
||||
# MEV Bot Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
The DBIS MEV Bot is a TypeScript application that monitors positions and executes profitable atomic amortization cycles, arbitrage opportunities, and protective deleveraging.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core Components
|
||||
|
||||
1. **Bot Engine** (`bot.ts`)
|
||||
- Main event loop
|
||||
- Strategy coordination
|
||||
- Opportunity detection
|
||||
|
||||
2. **Strategies**
|
||||
- **Amortization**: Executes amortization cycles
|
||||
- **Arbitrage**: Finds arbitrage opportunities
|
||||
- **Deleverage**: Protects positions with low HF
|
||||
|
||||
3. **Utilities**
|
||||
- **Invariant Checker**: Verifies invariants before execution
|
||||
- **Position Calculator**: Calculates position metrics
|
||||
- **Bundle Builder**: Builds Flashbots bundles
|
||||
|
||||
4. **Providers**
|
||||
- **Flash Router Client**: Interacts with FlashLoanRouter
|
||||
- **Aave Client**: Reads Aave position data
|
||||
- **Uniswap Client**: Executes swaps
|
||||
|
||||
## Setup
|
||||
|
||||
### 1. Install Dependencies
|
||||
|
||||
```bash
|
||||
cd mev-bot
|
||||
npm install
|
||||
```
|
||||
|
||||
### 2. Configure Environment
|
||||
|
||||
Create `.env` in `mev-bot/`:
|
||||
|
||||
```env
|
||||
RPC_URL=https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY
|
||||
PRIVATE_KEY=your_bot_private_key
|
||||
FLASH_ROUTER_ADDRESS=0x...
|
||||
VAULT_ADDRESS=0x...
|
||||
KERNEL_ADDRESS=0x...
|
||||
AAVE_POOL_ADDRESS=0x...
|
||||
UNISWAP_ROUTER_ADDRESS=0x...
|
||||
```
|
||||
|
||||
### 3. Build
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
### 4. Run
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
## Strategies
|
||||
|
||||
### Amortization Strategy
|
||||
|
||||
**Purpose**: Execute profitable amortization cycles
|
||||
|
||||
**Detection**:
|
||||
1. Check current position
|
||||
2. Calculate potential improvement
|
||||
3. Estimate gas costs
|
||||
4. Determine profitability
|
||||
|
||||
**Execution**:
|
||||
1. Verify invariants
|
||||
2. Build transaction
|
||||
3. Submit via Flashbots (if enabled)
|
||||
4. Monitor execution
|
||||
|
||||
### Arbitrage Strategy
|
||||
|
||||
**Purpose**: Find arbitrage opportunities
|
||||
|
||||
**Detection**:
|
||||
1. Compare prices across DEXs
|
||||
2. Calculate potential profit
|
||||
3. Account for gas and fees
|
||||
4. Determine if profitable
|
||||
|
||||
**Execution**:
|
||||
1. Execute arbitrage trade
|
||||
2. Capture profit
|
||||
3. Update position
|
||||
|
||||
### Deleverage Strategy
|
||||
|
||||
**Purpose**: Protect position when HF is low
|
||||
|
||||
**Trigger**: Health factor < 1.10
|
||||
|
||||
**Action**:
|
||||
1. Reduce leverage
|
||||
2. Improve health factor
|
||||
3. Prevent liquidation risk
|
||||
|
||||
## Bundle Building
|
||||
|
||||
### Flashbots Integration
|
||||
|
||||
For private transaction submission:
|
||||
|
||||
```typescript
|
||||
import { FlashbotsBundleProvider } from "@flashbots/ethers-provider-bundle";
|
||||
|
||||
const bundle = await bundleBuilder.buildBundle(transactions);
|
||||
await flashbotsProvider.sendBundle(bundle, targetBlockNumber);
|
||||
```
|
||||
|
||||
### Benefits
|
||||
- No front-running
|
||||
- Atomic execution
|
||||
- Priority inclusion
|
||||
|
||||
## Monitoring
|
||||
|
||||
### Position Monitoring
|
||||
|
||||
```typescript
|
||||
const position = await positionCalculator.getPosition();
|
||||
console.log(`HF: ${position.healthFactor}`);
|
||||
console.log(`LTV: ${position.ltv}`);
|
||||
console.log(`Collateral: ${position.collateral}`);
|
||||
console.log(`Debt: ${position.debt}`);
|
||||
```
|
||||
|
||||
### Alert Conditions
|
||||
|
||||
- Health factor < 1.10
|
||||
- Position at risk
|
||||
- Policy denial
|
||||
- Transaction failure
|
||||
- Bot downtime
|
||||
|
||||
## Multi-Region Deployment
|
||||
|
||||
Deploy in multiple regions for redundancy:
|
||||
- US East
|
||||
- EU
|
||||
- Singapore
|
||||
|
||||
Use leader election or load balancing.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Poll Interval
|
||||
Adjust how often bot checks for opportunities:
|
||||
```typescript
|
||||
private pollInterval = 5000; // 5 seconds
|
||||
```
|
||||
|
||||
### Profitability Thresholds
|
||||
Minimum profit to execute:
|
||||
```typescript
|
||||
const minProfit = ethers.parseEther("0.01"); // 0.01 ETH
|
||||
```
|
||||
|
||||
### Gas Price Management
|
||||
Set max gas price:
|
||||
```typescript
|
||||
const maxGasPrice = ethers.parseUnits("100", "gwei");
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Retry Logic
|
||||
```typescript
|
||||
async executeWithRetry(operation, maxRetries = 3) {
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (error) {
|
||||
if (i === maxRetries - 1) throw error;
|
||||
await sleep(1000 * (i + 1)); // Exponential backoff
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Failure Notifications
|
||||
Send alerts on:
|
||||
- Transaction failures
|
||||
- Invariant violations
|
||||
- Policy denials
|
||||
- Bot crashes
|
||||
|
||||
## Logging
|
||||
|
||||
Use Winston for structured logging:
|
||||
|
||||
```typescript
|
||||
import winston from "winston";
|
||||
|
||||
const logger = winston.createLogger({
|
||||
level: "info",
|
||||
format: winston.format.json(),
|
||||
transports: [
|
||||
new winston.transports.File({ filename: "error.log", level: "error" }),
|
||||
new winston.transports.File({ filename: "combined.log" })
|
||||
]
|
||||
});
|
||||
```
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
1. **Batch Operations**: Group multiple checks
|
||||
2. **Caching**: Cache position data
|
||||
3. **Async Processing**: Parallel opportunity detection
|
||||
4. **Connection Pooling**: Reuse RPC connections
|
||||
|
||||
## Security
|
||||
|
||||
1. **Private Key Management**: Use secure key storage
|
||||
2. **Access Control**: Limit bot permissions
|
||||
3. **Rate Limiting**: Prevent spam
|
||||
4. **Monitoring**: Track all bot actions
|
||||
|
||||
## Deployment
|
||||
|
||||
### Docker
|
||||
|
||||
```dockerfile
|
||||
FROM node:18
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
CMD ["npm", "start"]
|
||||
```
|
||||
|
||||
### Systemd Service
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=DBIS MEV Bot
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=dbis
|
||||
WorkingDirectory=/opt/dbis-mev-bot
|
||||
ExecStart=/usr/bin/npm start
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
## Metrics
|
||||
|
||||
Track:
|
||||
- Opportunities detected
|
||||
- Cycles executed
|
||||
- Profit generated
|
||||
- Gas costs
|
||||
- Success rate
|
||||
- Average HF improvement
|
||||
|
||||
Reference in New Issue
Block a user