docs: Update onchain/CLAUDE.md with debugging insights

Added critical implementation details discovered during floor position debugging:
- VWAPTracker stores price² (squared) in X96 format
- Token calculation gotchas for Amount0/Amount1 functions
- Outstanding supply calculation details
- ETH scarcity sqrt calculation
- Precise optimizer parameter formulas

Made documentation more concise (133→108 lines) while adding actionable debugging tips.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
johba 2025-08-18 18:10:34 +02:00
parent f4ae2fea7a
commit e04885ad8a

View file

@ -1,133 +1,108 @@
# Smart Contracts - CLAUDE.md
# Smart Contracts
This directory contains the core smart contracts for the KRAIKEN protocol.
Core KRAIKEN protocol contracts implementing the dominant liquidity manager strategy.
## Architecture Overview
## Core Contracts
### Core Contracts
**Kraiken.sol** - ERC20 with Harberger staking
- `outstandingSupply()` = totalSupply - liquidityManager balance
- Proportional staking pool growth/shrink on mint/burn
- 20% supply cap (20k positions max)
**Kraiken.sol** - ERC20 token with Harberger tax staking
- Controlled minting exclusively by LiquidityManager
- Tax collection and redistribution mechanism
- 20% supply cap for staking (20,000 positions)
**LiquidityManager.sol** - Three-position strategy
- ANCHOR: Near price (1-100% width)
- DISCOVERY: Borders anchor (11k tick spacing)
- FLOOR: Deep liquidity at VWAP-adjusted price
- Asymmetric slippage prevents arbitrage
**LiquidityManager.sol** - Dominant liquidity provider
- Three-position anti-arbitrage strategy (ANCHOR, DISCOVERY, FLOOR)
- Dynamic parameter adjustment via Optimizer contract
- Asymmetric slippage profile prevents profitable arbitrage
**VWAPTracker.sol** - Historical price memory
- **Stores price² (squared) in X96 format**
- Records anchor midpoint on scrape
- Max 1000x compression on overflow
- `getAdjustedVWAP()` applies capital inefficiency
**VWAPTracker.sol** - Price memory protection
- Volume-weighted average with data compression (max 1000x)
- Prevents dormant whale manipulation
**Optimizer.sol** - Dynamic parameters
- Reads staking sentiment (% staked, avg tax)
- Returns 4 params for position adjustment
- Upgradeable for new strategies
**Optimizer.sol** - Dynamic parameter optimization
- Analyzes staking sentiment (% staked, average tax)
- Returns four key parameters for liquidity management
- Upgradeable for future algorithms
**Stake.sol** - Harberger tax implementation
**Stake.sol** - Harberger tax
- Self-assessed valuations
- Continuous auction mechanism
- Self-assessed valuations create prediction market
### Three-Position Strategy
## Critical Implementation Details
**ANCHOR**: Near current price, fast price discovery (1-100% width)
**DISCOVERY**: Borders anchor, captures fees (11000 tick spacing)
**FLOOR**: Deep liquidity at VWAP-adjusted prices
### Token Calculations
When `token0isWeth = true`:
- Amount0 functions return **ETH** amounts
- Amount1 functions return **KRAIKEN** amounts
- Discovery position must use `getAmount1ForLiquidity()` for KRAIKEN
**Technical Specs**:
- Fee Tier: 1% (10,000 basis points)
- Tick Spacing: 200 (base), 11,000 (discovery)
- Price Validation: 5-minute TWAP, 50-tick tolerance
### Outstanding Supply
Excludes tokens used for liquidity positions:
```solidity
outstandingSupply -= pulledHarb; // Anchor KRAIKEN
outstandingSupply -= discoveryAmount; // Discovery KRAIKEN
```
### Optimizer Parameters
### ETH Scarcity Check
```solidity
// VWAP is price² in X96, must take sqrt
uint256 sqrtVwapX96 = Math.sqrt(vwapX96) << 48;
uint256 requiredEth = outstandingSupply.mulDiv(sqrtVwapX96, 1 << 96);
```
1. **capitalInefficiency** (0 to 1e18): Capital buffer level
2. **anchorShare** (0 to 1e18): % of non-floor ETH in anchor
3. **anchorWidth** (0 to 100): Anchor position width %
4. **discoveryDepth** (0 to 1e18): Discovery liquidity density (2x-10x)
## Optimizer Parameters
1. **capitalInefficiency** (0-1e18)
- 0% = KRAIKEN valued at 70% for reserves
- 100% = KRAIKEN valued at 170% for reserves
2. **anchorShare** (0-1e18)
- Floor ETH = totalETH × (1 - anchorShare)²
- 95% anchorShare = 90.1% floor allocation
3. **anchorWidth** (0-100)
- % of current price for anchor range
4. **discoveryDepth** (0-1e18)
- 2x-10x liquidity multiplier vs anchor
## Fuzzing Analysis
Test strategy resilience across market conditions:
```bash
# Quick test (50 runs, position CSV)
./analysis/run-fuzzing.sh BullMarketOptimizer debugCSV
# Full campaign (custom runs/trades)
./analysis/run-fuzzing.sh WhaleOptimizer runs=100 trades=30
```
**Optimizers**: Bull, Bear, Neutral, Whale, Random
**Output**: `fuzzing_results_[optimizer]_[timestamp]/`
- Position CSVs show tick placement
- Summary shows profitable scenarios
## Development
```bash
forge build # Build contracts
forge test # Run tests
forge test --gas-report # Gas optimization
forge test --fuzz-runs 10000 # Extended fuzzing
forge build # Compile
forge test # Run tests
forge test -vvv # Debug mode
forge test --mc Test # Match contract
```
## Testing
**Debugging Tips**:
- Check positions CSV for tick placement
- Verify token types in calculations
- Use EthScarcity events for diagnostics
- `test/helpers/UniswapTestBase.sol` - Uniswap integration base
- `test/helpers/KraikenTestBase.sol` - Common utilities
- Key tests: LiquidityManager.t.sol, Stake.t.sol, VWAPTracker.t.sol
## Key Files
## Code Guidelines
- **Check lib/uni-v3-lib** for existing Uniswap math
- **Use test/helpers** for common patterns
- **Security**: Reentrancy protection, oracle validation
- **Gas**: Batch operations, optimize storage
## Analysis Tools
### Fuzzing Analysis
Tools for testing KRAIKEN's three-position strategy resilience against various market conditions and trading patterns.
#### Quick Start
```bash
# Run with specific optimizer (50 runs default)
./analysis/run-fuzzing.sh BullMarketOptimizer
# Custom runs and trades
./analysis/run-fuzzing.sh WhaleOptimizer runs=100 trades=30
# Debug mode with position tracking CSV (forces runs=1)
./analysis/run-fuzzing.sh NeutralMarketOptimizer debugCSV
```
#### Available Optimizers
- `BullMarketOptimizer` - Buying bias
- `NeutralMarketOptimizer` - Balanced trading
- `BearMarketOptimizer` - Selling bias
- `WhaleOptimizer` - Large positions
- `RandomScenarioOptimizer` - Random behavior
#### Output Structure
Each campaign creates `fuzzing_results_[optimizer]_[timestamp]/`:
- `config.txt` - Campaign parameters
- `run_*.log` - Individual run logs
- `merged_profitable_scenarios.csv` - Profitable scenarios combined
- `summary.txt` - Statistics and cumulative P&L
- `debug_positions_*.csv` - Position data (debugCSV mode only)
#### Visualization
```bash
# Automatic launch with debugCSV
./analysis/run-fuzzing.sh [optimizer] debugCSV
# Manual server (port 8000)
./analysis/view-scenarios.sh
```
#### Advanced Usage
```bash
# Manual fuzzing with environment variables
FUZZING_RUNS=500 TRACK_POSITIONS=true forge script analysis/FuzzingAnalysis.s.sol --ffi --via-ir
```
Environment variables:
- `FUZZING_RUNS` - Scenarios per market (default: 100)
- `TRACK_POSITIONS` - Enable position CSV (default: false)
- `OPTIMIZER_CLASS` - Optimizer to use
- `TRADES_PER_RUN` - Trades per run (default: 20)
## Uniswap V3 Math
See [UNISWAP_V3_MATH.md](UNISWAP_V3_MATH.md) for detailed math concepts.
- `test/helpers/UniswapTestBase.sol` - Pool setup
- `test/helpers/KraikenTestBase.sol` - Common utils
- `lib/uni-v3-lib/` - Uniswap V3 math
- [UNISWAP_V3_MATH.md](UNISWAP_V3_MATH.md) - Math reference