This commit is contained in:
johba 2025-08-09 18:03:31 +02:00
parent 5b376885fd
commit 9f0b163303
19 changed files with 1340 additions and 490 deletions

View file

@ -1,92 +1,114 @@
# KRAIKEN Liquidity Analysis
# KRAIKEN Fuzzing Analysis Tools
Analysis tools for testing the three-position anti-arbitrage strategy using random fuzzing to discover profitable trading scenarios.
This directory contains tools for fuzzing the KRAIKEN LiquidityManager to identify potential profitable trading scenarios.
## Quick Start
1. **Run the analysis** (includes parameter validation + random fuzzing):
```bash
forge script analysis/SimpleAnalysis.s.sol --ffi --via-ir
```
2. **Start visualization server**:
```bash
cd analysis && python3 -m http.server 8000
```
3. **View results** at `http://localhost:8000/scenario-visualizer.html`
## How It Works
The analysis script uses **random fuzzing** like the historical `testScenarioFuzz` function to discover profitable trading scenarios:
- **Random Parameters**: Generates random trading amounts, frequencies, and sentiment parameters
- **Historical Logic**: Uses exact trading logic from the working historical tests
- **Early Exit**: Stops immediately after finding the first profitable scenario
- **CSV Generation**: Creates detailed trading sequence data for visualization
## Analysis Commands
### Full Analysis (Recommended)
```bash
forge script analysis/SimpleAnalysis.s.sol --ffi --via-ir
```
Runs both parameter validation and random fuzzing analysis.
# Run fuzzing with default settings (50 runs, 20 trades)
./run-fuzzing.sh BullMarketOptimizer
### Parameter Validation Only
Modify the `run()` function to comment out `runSentimentFuzzingAnalysis()` if you only want to test parameter configurations.
# Run with custom parameters
./run-fuzzing.sh WhaleOptimizer runs=100 trades=50
# Clean up generated files
./clean.sh
```
## Files
- `SimpleAnalysis.s.sol` - Main analysis script with random fuzzing
- `scenario-visualizer.html` - Web-based position visualization
- `profitable_scenario.csv` - Generated when profitable scenarios are found
- `view-scenarios.sh` - HTTP server launcher (alternative to python server)
### Core Scripts
- `FuzzingAnalysis.s.sol` - Main Solidity fuzzing script that tests trading scenarios
- `run-fuzzing.sh` - Shell script to orchestrate multiple fuzzing runs
- `clean.sh` - Cleanup script to remove generated files
## Analysis Output
### Console Output
- Parameter validation results for bull/neutral/bear market conditions
- Random fuzzing attempts with generated parameters
- Profitable scenario detection and stopping logic
### CSV Data
When profitable scenarios are found, generates `profitable_scenario.csv` containing:
- Trading sequence (buy/sell/recenter actions)
- Position data (Floor/Anchor/Discovery liquidity amounts)
- Price tick information
- Token distribution across positions
### Helpers
- `helpers/SwapExecutor.sol` - Handles swap execution through Uniswap
- `helpers/CSVManager.sol` - CSV generation utilities
- `helpers/CSVHelper.sol` - CSV formatting helpers
### Visualization
Interactive HTML dashboard showing:
- Position ranges and token distributions
- Uniswap V3 liquidity calculations
- Trading sequence progression
- Anti-arbitrage strategy effectiveness
- `AnalysisVisualizer.py` - Python script to generate charts from CSV data
- `scenario-visualizer.html` - Interactive web visualization
- `view-scenarios.sh` - Quick script to launch web server for visualization
## Random Fuzzing Details
## Available Optimizers
The script generates random parameters for each test:
- **Actions**: 6-12 trading actions per scenario
- **Frequency**: 1-5 recenter frequency
- **Amounts**: 50-255 basis values (scaled to ether)
- **Sentiment**: Random capital inefficiency, anchor share, width, discovery depth
- `BullMarketOptimizer` - Aggressive parameters for bull market conditions
- `NeutralMarketOptimizer` - Balanced parameters
- `BearMarketOptimizer` - Conservative parameters for bear market conditions
- `WhaleOptimizer` - Simulates large position dominance
- `MockOptimizer` - Standard mock with configurable parameters
- `RandomScenarioOptimizer` - Randomized parameters for each run
This approach mirrors the historical `testScenarioFuzz` function that successfully found profitable scenarios in the original codebase.
## Usage
## Troubleshooting
### Running Fuzzing Campaigns
### No Profitable Scenarios Found
- The anti-arbitrage protection is working effectively
- Try increasing `maxAttempts` in `runSentimentFuzzingAnalysis()` for more fuzzing attempts
- Check console output for parameter validation results
```bash
# Basic usage
./run-fuzzing.sh <optimizer_class> [runs=N] [trades=N]
### Script Execution Issues
- Ensure you're using the full script command (not `-s` function selection)
- The `setUp()` function is required for proper contract initialization
- Use `--via-ir` flag for complex contract compilation
# Examples
./run-fuzzing.sh BullMarketOptimizer # Uses defaults
./run-fuzzing.sh WhaleOptimizer runs=100 # 100 runs
./run-fuzzing.sh BearMarketOptimizer trades=50 # 50 trades per run
./run-fuzzing.sh NeutralMarketOptimizer runs=25 trades=30 # Both params
```
### Visualization Issues
- Start the HTTP server from the `analysis/` directory
- Check that `profitable_scenario.csv` exists before viewing
- Browser security may block local file access - use the HTTP server
Parameters:
- `optimizer_class` - Required. The optimizer class to use
- `runs=N` - Optional. Number of fuzzing runs (default: 50)
- `trades=N` - Optional. Trades per run (default: 20, actual will be ±5)
### Output
Each fuzzing campaign creates a timestamped directory with:
- Individual run logs (`run_N.log`)
- Merged CSV of profitable scenarios
- Summary report with statistics
- Configuration file for reproducibility
### Visualization
To visualize results:
```bash
# Start local web server
./view-scenarios.sh
# Or use Python directly
python3 -m http.server 8000
# Then open http://localhost:8000/scenario-visualizer.html
```
### Cleanup
Remove all generated files:
```bash
./clean.sh
```
## Environment Variables
The fuzzing script supports these environment variables:
- `FUZZING_RUNS` - Number of runs (overridden by script parameter)
- `OPTIMIZER_CLASS` - Optimizer to use (overridden by script parameter)
- `TRADES_PER_RUN` - Trades per run (overridden by script parameter)
- `TRACK_POSITIONS` - Enable detailed position tracking (default: false)
## Development
To add a new optimizer:
1. Create the optimizer contract in `../test/mocks/`
2. Import it in `FuzzingAnalysis.s.sol`
3. Add it to the `_getOptimizerByClass` function
4. Update this README
## Notes
- Each run deploys a fresh Uniswap V3 environment
- Gas limit is set to 200M for --via-ir compilation
- Results are deterministic based on the seed
- The fuzzer tests random buy/sell patterns with periodic recenters