harb/TECHNICAL_APPENDIX.md
openhands 85350caf52 feat: OptimizerV3 with direct 2D staking-to-LP parameter mapping
Core protocol changes for launch readiness:

- OptimizerV3: binary bear/bull mapping from (staking%, avgTax) — avoids
  exploitable AW 30-90 kill zone. Bear: AS=30%, AW=100, CI=0, DD=0.3e18.
  Bull: AS=100%, AW=20, CI=0, DD=1e18. UUPS upgradeable with __gap[48].
- Directional VWAP: only records prices on ETH inflow (buys), preventing
  sell-side dilution of price memory
- Floor formula: unified max(scarcity, mirror, clamp) — VWAP mirror uses
  distance from adjusted VWAP as floor distance, no branching
- PriceOracle (M-1 fix): correct fallback TWAP divisor (60000s, not 300s)
- Access control (M-2 fix): deployer-only guard on one-time setters
- Recenter rate limit (M-3 fix): 60-second cooldown for open recenters
- Safe fallback params: recenter() optimizer-failure defaults changed from
  exploitable CI=50%/AW=50 to safe bear-mode CI=0/AW=100
- Recentered event for monitoring and indexing
- VERSION bump to 2, kraiken-lib COMPATIBLE_CONTRACT_VERSIONS updated

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 18:21:18 +00:00

156 lines
7.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Technical Appendix
This document provides detailed technical analysis and implementation details for the KRAIKEN protocol's core innovations. For a high-level overview, see AGENTS.md.
## Asymmetric Slippage Strategy
### The Core Innovation
The three-position liquidity structure creates an "unfair advantage" against traditional arbitrageurs by forcing asymmetric costs on round-trip trades.
### Trade-Recenter-Reverse Attack Pattern
1. **Setup**: Trader identifies predictable rebalancing trigger
2. **Exploit**: Large trade → triggers recenter() → reverse trade at new configuration
3. **Expected Profit**: Trader profits from predictable liquidity movements
4. **Reality**: Asymmetric slippage makes this unprofitable
### Protection Mechanism
**Position Architecture:**
- **ANCHOR**: Shallow liquidity (~current price) = high slippage, fast price movement
- **DISCOVERY**: Medium liquidity (borders anchor) = fee capture zone
- **FLOOR**: Deep liquidity (VWAP-adjusted) = low slippage, price memory
**Attack Protection Logic:**
1. **First Trade**: Price moves quickly through shallow ANCHOR → hits deep DISCOVERY/FLOOR liquidity (high slippage cost)
2. **Recenter**: Rebalances all positions around new price
3. **Reverse Trade**: Price moves through new shallow ANCHOR → hits opposite deep liquidity (high slippage cost again)
4. **Result**: Attacker pays high slippage twice, making round-trip unprofitable
### Mathematical Foundation
The slippage differential between ANCHOR (shallow) and FLOOR (deep) positions ensures that any round-trip trade pays disproportionate costs, protecting the protocol's liquidity from exploitation.
## Dormant Whale Protection
### The Problem
**Dormant Whale Attack Pattern:**
1. **Accumulation**: Whale buys large amounts early at cheap prices
2. **Dormancy**: Waits extended periods while protocol accumulates volume and prices rise
3. **Exploitation**: Attempts to sell at inflated prices when market conditions are favorable
4. **Impact**: Can crash token price using historical price advantages
### VWAP-Based Solution
**Core Mechanism:**
- **Historical Price Memory**: VWAP tracker maintains volume-weighted average pricing across time
- **FLOOR Position Integration**: Only FLOOR position uses VWAP for price memory (ANCHOR/DISCOVERY use current tick)
- **Compression Algorithm**: Data compression (max 1000x) preserves historical significance while managing storage
### Double-Overflow Analysis
**Stress Testing Results:**
Double-overflow scenarios requiring >1000x compression would need:
- Single transactions >10,000 ETH (unrealistic for any individual)
- Token prices >$4.3 billion (exceeds global wealth)
- **Conclusion**: 1000x compression limit provides adequate protection against realistic scenarios
### Implementation Details
**FLOOR Position Calculation (Unified Formula):**
```
floorTick = max(scarcityTick, mirrorTick, clampTick) toward KRK-cheap side
```
Three signals determine the floor:
- **scarcityTick**: derived from `vwapX96` and ETH/supply ratio. Dominates when ETH is scarce.
- **mirrorTick**: `currentTick + |adjustedVwapTick - currentTick|` on KRK-cheap side. Reflects VWAP distance symmetrically. During sell pressure the mirror distance grows, resisting floor walkdown.
- **clampTick**: minimum distance from anchor edge. `anchorSpacing = 200 + (34 × 20 × AW / 100)` ticks.
**VWAP Mirror Defense:**
- During sell-heavy trading, the current tick drops but VWAP stays higher, so mirror distance *grows* — floor naturally resists being walked down.
- CI controls mirror distance through `getAdjustedVWAP(CI)` with no magic numbers. CI=0% is safest (proven zero effect on fee revenue).
**Directional VWAP Recording:**
- VWAP only records on ETH inflow (buys into the LM), preventing attackers from diluting VWAP with sells.
- `shouldRecordVWAP` compares `lastRecenterTick` to current tick to detect direction.
**Protection Mechanism:**
- VWAP provides "eternal memory" of historical trading activity
- Compression algorithm ensures memory persists even under extreme volume
- FLOOR position acts as price anchor preventing manipulation of historical price disparities
## Harberger Tax Sentiment Oracle
### Mechanism Design
**Continuous Auction Model:**
- Stakers self-assign tax rates on their positions
- Higher tax rates signal higher confidence in token value
- Positions can be "snatched" by paying higher tax rates
- Creates prediction market for token value through tax rate signals
### Data Collection
**Sentiment Metrics:**
- **Percentage Staked**: What portion of total supply is staked
- **Average Tax Rate**: Weighted average of all staking tax rates
- **Tax Rate Distribution**: Spread of tax rates across stakers
### OptimizerV3 Integration
**Direct 2D Binary Mapping (no intermediate score):**
OptimizerV3 reads `percentageStaked` and `averageTaxRate` from the Stake contract and maps them directly to one of two configurations:
- `staked ≤ 91%` → always **BEAR**: AS=30%, AW=100, CI=0, DD=0.3e18
- `staked > 91%`**BULL** if `deltaS³ × effIdx / 20 < 50`: AS=100%, AW=20, CI=0, DD=1e18
The binary step avoids the AW 40-80 kill zone where intermediate parameters are exploitable. Bull requires >91% staked with low enough tax; any decline snaps to bear instantly.
**Parameter Safety (proven via 1050-combo 4D sweep):**
- CI=0% always (zero effect on fee revenue, maximum protection)
- Fee revenue is parameter-independent (~1.5 ETH/cycle across all combos)
- Safety comes entirely from the AS×AW configuration
### Economic Incentives
- **Tax Revenue**: Funds protocol operations and incentivizes participation
- **Staking Benefits**: Percentage ownership of total supply (rather than fixed token amounts)
- **Prediction Market**: Tax rates create market-based sentiment signals
- **Liquidity Optimization**: Sentiment data feeds into binary bear/bull parameter selection
## Position Dependencies Technical Details
### Execution Order: ANCHOR → DISCOVERY → FLOOR
**Economic Dependencies:**
1. **ANCHOR → DISCOVERY**: Discovery liquidity amount depends on KRAIKEN minted by ANCHOR position
2. **ANCHOR + DISCOVERY → FLOOR**: FLOOR must defend against maximum selling pressure from final circulating supply
3. **VWAP Exclusivity**: Only FLOOR uses VWAP for historical price memory; ANCHOR/DISCOVERY use current tick
**Design Rationale:**
- **ANCHOR**: Immediate price discovery and fast market response
- **DISCOVERY**: Fee capture from trades that move through ANCHOR
- **FLOOR**: Historical price anchoring and whale protection
### Recentering Trigger
**Open Access Design:**
- Any address can call `recenter()` when conditions are met
- Incentivizes community participation in protocol maintenance
- Removes single point of failure from automated systems
- Trigger conditions based on price movement thresholds
### Critical Success Metrics
**Dominant Position Requirement:**
- LiquidityManager must trade majority of token supply
- If position becomes non-dominant, project fails
- Analysis tools in `/onchain/analysis/` monitor this metric
- Growth mechanism depends on maintaining liquidity dominance
## Implementation References
### Key Contracts
- **LiquidityManager.sol**: Core three-position strategy implementation
- **VWAPTracker.sol**: Historical price memory and compression algorithm
- **OptimizerV3.sol**: Sentiment-driven binary bear/bull parameter selection (UUPS upgradeable)
- **Stake.sol**: Harberger tax mechanism and sentiment data collection
### Analysis Tools
- **`/onchain/analysis/`**: Growth mechanism demonstrations and scenario testing
- **Fuzzing Tests**: Stress testing of position strategies and edge cases
- **Scenario Visualization**: Tools for understanding liquidity dynamics
### Related Documentation
- **AGENTS.md**: High-level overview and development guidance
- **`/onchain/analysis/README.md`**: Detailed analysis tool usage