Fix token assignment issue in ThreePositionStrategy and improve analysis tools
- Fix token assignment bug in discovery and floor position calculations - Correct economic model: Floor holds ETH, Discovery holds KRAIKEN - Update scenario visualizer labels and token assignments - Add comprehensive CSV generation with realistic token distributions - Consolidate analysis tools into SimpleAnalysis.s.sol with debugging functions - Update README with streamlined analysis instructions - Clean up analysis folder structure for better organization 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
74143dfac7
commit
7f3810a871
6 changed files with 866 additions and 460 deletions
|
|
@ -1,328 +1,28 @@
|
|||
# Scenario Analysis Suite
|
||||
# KRAIKEN Liquidity Analysis
|
||||
|
||||
This directory contains tools for deep analysis of LiquidityManagerV2 trading scenarios, separate from unit testing.
|
||||
Quick analysis tools for testing the three-position anti-arbitrage strategy.
|
||||
|
||||
## Overview
|
||||
## Usage
|
||||
|
||||
The Scenario Analysis Suite is designed for **research and development**, not unit testing. It analyzes the new modular LiquidityManagerV2 architecture to identify:
|
||||
1. **Run sentiment analysis** to find profitable scenarios:
|
||||
```bash
|
||||
forge script analysis/SimpleAnalysis.s.sol:SimpleAnalysis -s "runSentimentFuzzingAnalysis()" --ffi --via-ir
|
||||
```
|
||||
|
||||
- 🎯 **Profitable trading sequences** that could indicate protocol vulnerabilities
|
||||
- 🛡️ **MEV opportunities** and market manipulation potential
|
||||
- 🔍 **Edge cases** not covered by standard unit tests
|
||||
- 📊 **Performance characteristics** under different market conditions
|
||||
- 🏗️ **Modular component interactions** and potential failure modes
|
||||
2. **Start visualization server**:
|
||||
```bash
|
||||
./view-scenarios.sh
|
||||
```
|
||||
|
||||
3. **View results** at `http://localhost:8001/scenario-visualizer.html`
|
||||
|
||||
## Files
|
||||
|
||||
```
|
||||
analysis/ # Analysis suite (excluded from forge test)
|
||||
├── README.md # This documentation
|
||||
├── SimpleAnalysis.s.sol # Lightweight analysis script
|
||||
├── scenario-visualizer.html # Interactive CSV data visualization
|
||||
├── view-scenarios.sh # Launch script for visualization server
|
||||
└── examples/ # Example analysis scripts
|
||||
├── batch_analysis.sh # Batch scenario runner
|
||||
└── profitable_scenarios/ # Output directory for profitable scenarios
|
||||
```
|
||||
- `SimpleAnalysis.s.sol` - Main analysis script with sentiment fuzzing
|
||||
- `scenario-visualizer.html` - Web-based position visualization
|
||||
- `view-scenarios.sh` - HTTP server launcher
|
||||
- `profitable_scenario.csv` - Generated results (if profitable scenarios found)
|
||||
|
||||
## Quick Start
|
||||
## Analysis Output
|
||||
|
||||
### 1. Basic Scenario Analysis
|
||||
|
||||
```bash
|
||||
# Run simple analysis script
|
||||
forge script analysis/SimpleAnalysis.s.sol --ffi -vvv
|
||||
|
||||
# View results in browser (starts server automatically)
|
||||
./analysis/view-scenarios.sh
|
||||
```
|
||||
|
||||
### 2. Standard Unit Testing (Default)
|
||||
|
||||
```bash
|
||||
# Run all unit tests (fast, no analysis)
|
||||
forge test
|
||||
|
||||
# This runs ONLY unit tests, excludes analysis scripts
|
||||
# Perfect for CI/CD and regular development
|
||||
```
|
||||
|
||||
### 3. Batch Analysis
|
||||
|
||||
```solidity
|
||||
// Prepare multiple scenarios
|
||||
uint8[] memory numActionsArray = new uint8[](3);
|
||||
numActionsArray[0] = 10; numActionsArray[1] = 20; numActionsArray[2] = 30;
|
||||
|
||||
uint8[] memory frequencyArray = new uint8[](3);
|
||||
frequencyArray[0] = 2; frequencyArray[1] = 5; frequencyArray[2] = 10;
|
||||
|
||||
uint8[][] memory amountsArray = new uint8[][](3);
|
||||
// ... populate amounts arrays ...
|
||||
|
||||
analysis.batchAnalyzeScenarios(numActionsArray, frequencyArray, amountsArray);
|
||||
```
|
||||
|
||||
## Understanding Results
|
||||
|
||||
### Console Output
|
||||
|
||||
```
|
||||
🔬 Starting batch scenario analysis...
|
||||
Total scenarios to analyze: 5
|
||||
|
||||
--- Analyzing scenario 1 of 5 ---
|
||||
Scenario 1 :
|
||||
Actions: 10 | Frequency: 3
|
||||
Tick movement: -123891 → 245673
|
||||
Result: Protected ✅
|
||||
Gas used: 2847291
|
||||
|
||||
🚨 PROFITABLE SCENARIO DETECTED 🚨
|
||||
═══════════════════════════════════
|
||||
Scenario ID: 3
|
||||
Profit extracted: 0.025 ETH
|
||||
Actions performed: 15
|
||||
Recentering frequency: 5
|
||||
Price movement: -98234 → 156789
|
||||
Gas used: 3421098
|
||||
Trading amounts:
|
||||
[ 0 ]: 125
|
||||
[ 1 ]: 67
|
||||
...
|
||||
CSV written to: ./out/profitable_scenario_3.csv
|
||||
═══════════════════════════════════
|
||||
|
||||
📊 ANALYSIS SUMMARY
|
||||
══════════════════════
|
||||
Total scenarios analyzed: 5
|
||||
Profitable scenarios found: 1
|
||||
Profit rate: 20 %
|
||||
Total profit extracted: 0.025 ETH
|
||||
Average profit per profitable scenario: 0.025 ETH
|
||||
══════════════════════
|
||||
```
|
||||
|
||||
### CSV Output Files
|
||||
|
||||
When profitable scenarios are detected, detailed CSV files are generated:
|
||||
|
||||
- `./analysis/profitable_scenario.csv` - Complete position and price data
|
||||
- Contains tick-by-tick pool state for visual analysis
|
||||
- Automatically loaded by scenario-visualizer.html for visualization
|
||||
- Can also be imported into Excel/Google Sheets for charting
|
||||
|
||||
### Events for Programmatic Analysis
|
||||
|
||||
```solidity
|
||||
event ScenarioAnalyzed(
|
||||
uint256 indexed scenarioId,
|
||||
bool profitable,
|
||||
uint256 profit,
|
||||
uint8 numActions,
|
||||
uint8 frequency
|
||||
);
|
||||
|
||||
event ProfitableScenarioDetected(
|
||||
uint256 indexed scenarioId,
|
||||
uint256 profit,
|
||||
uint8 numActions,
|
||||
uint8 frequency,
|
||||
string csvFile
|
||||
);
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Analysis Parameters
|
||||
|
||||
```solidity
|
||||
// In ScenarioAnalysis.sol
|
||||
uint256 constant MAX_ANALYSIS_ACTIONS = 100; // Max trades per scenario
|
||||
uint256 constant PROFIT_THRESHOLD = 0.001 ether; // Min profit to record
|
||||
```
|
||||
|
||||
### Environment Setup
|
||||
|
||||
```bash
|
||||
# Enable file operations for CSV writing
|
||||
export FOUNDRY_FFI=true
|
||||
|
||||
# Increase gas limit for complex scenarios
|
||||
export FOUNDRY_GAS_LIMIT=50000000
|
||||
|
||||
# Set output directory
|
||||
mkdir -p test/analysis/output
|
||||
```
|
||||
|
||||
## Example Workflows
|
||||
|
||||
### 1. Protocol Security Audit
|
||||
|
||||
```bash
|
||||
# Test for MEV opportunities
|
||||
forge test --match-contract "ScenarioAnalysis" --match-test "analyzeScenario" --ffi
|
||||
|
||||
# Review profitable scenarios
|
||||
ls -la ./analysis/profitable_scenario.csv
|
||||
|
||||
# Visualize scenario data
|
||||
open ./analysis/scenario-visualizer.html
|
||||
|
||||
# Analyze patterns in profitable trades
|
||||
python scripts/analyze_profitable_scenarios.py
|
||||
```
|
||||
|
||||
### 2. Parameter Optimization
|
||||
|
||||
```solidity
|
||||
// Test different recentering frequencies
|
||||
for (uint8 freq = 1; freq <= 20; freq++) {
|
||||
analysis.analyzeScenario(10, freq, standardAmounts);
|
||||
}
|
||||
|
||||
// Analyze results to optimize frequency parameter
|
||||
analysis.getAnalysisStats();
|
||||
```
|
||||
|
||||
### 3. Stress Testing
|
||||
|
||||
```solidity
|
||||
// Test extreme scenarios
|
||||
uint8[] memory extremeAmounts = new uint8[](50);
|
||||
// Fill with edge case values...
|
||||
|
||||
analysis.analyzeScenario(50, 1, extremeAmounts); // High frequency
|
||||
analysis.analyzeScenario(50, 25, extremeAmounts); // Low frequency
|
||||
```
|
||||
|
||||
## Integration with Development Workflow
|
||||
|
||||
### Automatic Separation
|
||||
|
||||
```bash
|
||||
# Unit tests ONLY (default - fast, no file I/O)
|
||||
forge test
|
||||
|
||||
# Analysis scripts (explicit - slower, generates files)
|
||||
forge script analysis/SimpleAnalysis.s.sol --ffi
|
||||
|
||||
# Or use the batch script
|
||||
./analysis/examples/batch_analysis.sh
|
||||
```
|
||||
|
||||
### Git Integration
|
||||
|
||||
```gitignore
|
||||
# .gitignore
|
||||
test/analysis/output/
|
||||
test/analysis/profitable_scenarios/
|
||||
analysis/profitable_scenario.csv
|
||||
out/profitable_scenario_*.csv
|
||||
```
|
||||
|
||||
### Code Review Process
|
||||
|
||||
1. **Unit tests must pass** before analysis
|
||||
2. **Analysis results reviewed** for new vulnerabilities
|
||||
3. **Profitable scenarios investigated** and addressed
|
||||
4. **Parameters adjusted** based on analysis insights
|
||||
|
||||
## Best Practices
|
||||
|
||||
### ✅ Do
|
||||
|
||||
- Run analysis suite during **development and security reviews**
|
||||
- **Investigate ALL profitable scenarios** thoroughly
|
||||
- **Version control analysis scripts** but not output files
|
||||
- **Document findings** and protocol improvements
|
||||
- **Use analysis to guide parameter tuning**
|
||||
|
||||
### ❌ Don't
|
||||
|
||||
- Include analysis in **CI/CD pipelines** (too slow)
|
||||
- **Commit CSV output files** to git (too large)
|
||||
- **Use as replacement for unit tests** (different purposes)
|
||||
- **Ignore profitable scenarios** (potential vulnerabilities)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
```bash
|
||||
# Error: FFI not enabled
|
||||
export FOUNDRY_FFI=true
|
||||
|
||||
# Error: Gas limit exceeded
|
||||
export FOUNDRY_GAS_LIMIT=50000000
|
||||
|
||||
# Error: Output directory missing
|
||||
mkdir -p ./out
|
||||
|
||||
# Error: Memory limit reached
|
||||
# Reduce MAX_ANALYSIS_ACTIONS or run smaller batches
|
||||
```
|
||||
|
||||
### Performance Tips
|
||||
|
||||
- **Batch analysis** in smaller groups for better memory management
|
||||
- **Use specific test filters** to run targeted analysis
|
||||
- **Clean output directory** regularly to save disk space
|
||||
- **Monitor gas usage** and adjust limits as needed
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Custom Analysis Contracts
|
||||
|
||||
```solidity
|
||||
contract MyCustomAnalysis is ScenarioAnalysis {
|
||||
function analyzeSpecificPattern() public {
|
||||
// Your custom analysis logic
|
||||
uint8[] memory amounts = _generatePatternAmounts();
|
||||
analyzeScenario(15, 5, amounts);
|
||||
}
|
||||
|
||||
function _generatePatternAmounts() internal pure returns (uint8[] memory) {
|
||||
// Generate specific trading patterns for analysis
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Automated Analysis Scripts
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# batch_analysis.sh
|
||||
|
||||
echo "🔬 Running automated scenario analysis..."
|
||||
|
||||
for frequency in {1..10}; do
|
||||
for actions in {5..25..5}; do
|
||||
echo "Testing frequency=$frequency, actions=$actions"
|
||||
forge test --match-contract "ScenarioAnalysis" \
|
||||
--match-test "analyzeScenario($actions,$frequency," \
|
||||
--ffi --gas-limit 50000000
|
||||
done
|
||||
done
|
||||
|
||||
echo "📊 Analysis complete. Check ./out/ for results."
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
When adding new analysis features:
|
||||
|
||||
1. **Extend ScenarioAnalysis contract** for new analysis types
|
||||
2. **Add documentation** for new parameters and outputs
|
||||
3. **Include example usage** in this README
|
||||
4. **Test with various inputs** to ensure robustness
|
||||
5. **Update .gitignore** for new output file patterns
|
||||
|
||||
## Support
|
||||
|
||||
For questions about the analysis suite:
|
||||
|
||||
- Check this README first
|
||||
- Review existing analysis contracts for examples
|
||||
- Look at unit tests for basic usage patterns
|
||||
- Consult team for protocol-specific analysis needs
|
||||
The sentiment analysis tests bull/neutral/bear market conditions and generates CSV data for any profitable trading scenarios found. The visualizer shows position ranges, token distributions, and Uniswap V3 liquidity calculations.
|
||||
Loading…
Add table
Add a link
Reference in a new issue