Update documentation structure and add technical appendix

- Restructure CLAUDE.md to lead with unique technical innovations
- Add comprehensive TECHNICAL_APPENDIX.md with detailed analysis
- Focus on conceptual clarity for AI assistant guidance
- Merge redundant sections and condense development commands
- Clarify economic model and user journeys
- Add proper cross-references between documents

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
giteadmin 2025-07-18 20:40:42 +02:00
parent eac7360ff9
commit 80f0b8217c
2 changed files with 213 additions and 152 deletions

222
CLAUDE.md
View file

@ -2,176 +2,94 @@
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Overview ## Core Innovation
KRAIKEN is a multi-component DeFi protocol implementing a Harberger tax mechanism with dynamic liquidity provisioning. The project consists of: KRAIKEN is a token with a **dominant liquidity manager** that creates an unfair advantage in trading through:
- **Smart Contracts** (Solidity/Foundry) - Core protocol logic 1. **Asymmetric Slippage Strategy**: Three-position liquidity structure prevents profitable arbitrage against the protocol
- **TypeScript Library** (kraiken-lib) - Helper functions and GraphQL client 2. **Sentiment Oracle**: Harberger tax-based staking creates a prediction market for token value
- **Subgraph** (AssemblyScript) - Blockchain data indexing 3. **Dormant Whale Protection**: VWAP-based price memory prevents historical price manipulation
- **Transaction Bot** (Node.js) - Automated market making service
## Architecture **Critical Success Factor**: The liquidity manager must maintain its dominant position (trading most of the supply) - if it loses this, the project fails.
### Core Components ## Economic Model
1. **Kraiken Contract** (`onchain/src/Kraiken.sol`) - Main protocol contract implementing Harberger tax mechanism ### User Journeys
2. **Stake Contract** (`onchain/src/Stake.sol`) - Staking mechanism for sentiment data 1. **Token Holders**: Buy KRAIKEN on Uniswap → Hold to benefit from growing liquidity
3. **LiquidityManager Contract** (`onchain/src/LiquidityManager.sol`) - Uniswap V3 liquidity management 2. **Stakers**: Stake tokens at kraiken.org → Convert discrete tokens to percentage of total supply → Pay continuous tax rate (self-assigned) → Position can be "snatched" if someone pays higher tax
4. **Optimizer Contract** (`onchain/src/Optimizer.sol`) - Dynamic liquidity optimization
### Key Architecture Patterns ### Harberger Tax Mechanism
- Continuous auction model where stakers self-assign tax rates on their positions
- Creates prediction market for token value through tax rate signals
- Tax limited to 20% of total supply
- Optimizer contract analyzes percentage staked and average tax rate as sentiment data
- **Upgradeable Contracts**: Uses OpenZeppelin's upgradeable pattern ### Value Accrual
- **Uniswap V3 Integration**: Direct integration with Uniswap V3 for liquidity provision - Interlocking minting rights and liquidity management drive continuous growth
- **Genetic Algorithm Approach**: Plans to evolve liquidity strategies using on-chain algorithms - More liquidity strengthens token market position
- **Sentiment Oracle**: Uses staking data (% staked, average tax rate) as sentiment indicators - Analysis scripts in `/onchain/analysis/` demonstrate the growth mechanism
- Exact ETH growth → token value relationship is being researched
## Technical Architecture
### Core Contracts
**Kraiken.sol** - Main protocol contract implementing Harberger tax mechanism, token swaps, and tax collection
**LiquidityManager.sol** - Dominant liquidity provider with three-position anti-arbitrage strategy:
- Uses Optimizer contract for dynamic parameter adjustment
- Inherits from VWAPTracker for dormant whale protection
- **Key Feature**: Asymmetric slippage profile prevents profitable trade-recenter-reverse attacks
**VWAPTracker.sol** - "Eternal memory" protection against dormant whale attacks through volume-weighted average pricing with data compression (max 1000x)
**Optimizer.sol** - Analyzes staking sentiment data (% staked, average tax rate) and provides dynamic liquidity parameters. Upgradeable for future genetic algorithm implementation.
**Stake.sol** - Harberger tax-based staking mechanism that creates sentiment oracle through continuous auction of staking positions
### Position Strategy
**Order**: ANCHOR → DISCOVERY → FLOOR
- **ANCHOR**: Shallow liquidity around current price for fast price movement
- **DISCOVERY**: Proportional to KRAIKEN minted by anchor; borders anchor for fee capture
- **FLOOR**: Deep liquidity using VWAP-adjusted pricing for historical price memory
**Recentering**: Open to all, called whenever possible to maintain optimal positions
## Development Commands ## Development Commands
### Smart Contracts (onchain/) ### Essential Commands
```bash ```bash
# Setup dependencies # Smart Contracts
git submodule init forge build && forge test
git submodule update
cd lib/uni-v3-lib && yarn
# Build contracts # TypeScript Library
forge build npm test && npm run compile
# Run tests # Subgraph
forge test npm run codegen && npm run build
# Format code # Trigger Service
forge fmt
# Gas snapshots
forge snapshot
# Deploy (requires .env setup)
forge clean && forge cache clean
source .env
forge script script/BaseSepoliaDeploy.sol:BaseSepoliaDeploy --slow --broadcast --verify --rpc-url ${BASE_SEPOLIA_RPC_URL}
```
### TypeScript Library (harb-lib/)
```bash
# Run tests
npm test
# Generate GraphQL types
npm run compile
# Watch for changes
npm run watch
```
### Subgraph (subgraph/base_sepolia/)
```bash
# Generate code
npm run codegen
# Build subgraph
npm run build
# Deploy to The Graph
npm run deploy
# Run tests
npm run test
```
### Transaction Bot (services/txnBot/)
```bash
# Start service
node service.js node service.js
``` ```
## Key Contracts and Interfaces ### Analysis Tools
Critical for hardening the liquidity manager - see `onchain/analysis/README.md` for detailed usage and growth mechanism demonstrations.
### Kraiken.sol ## Key Files
- Main protocol contract implementing Harberger tax
- Integrates with Uniswap V3 for token swaps
- Manages tax collection and distribution
### LiquidityManager.sol - `onchain/src/LiquidityManager.sol` - Core liquidity strategy
- Handles Uniswap V3 position management - `onchain/src/Kraiken.sol` - Token and tax mechanism
- Implements recentering logic for dynamic liquidity - `onchain/src/Optimizer.sol` - Sentiment analysis and parameter optimization
- Uses UniswapHelpers for price calculations - `onchain/analysis/` - Growth mechanism analysis and scenario testing
- **VWAP Integration**: Inherits from VWAPTracker for dormant whale protection - `services/txnBot/` - Automated recentering and liquidation
- **Anti-Arbitrage Strategy**: Implements asymmetric slippage profile to protect against trade-recenter-reverse attacks
#### Trade-Recenter-Reverse Attack Protection ## Project Structure
**The Exploit Pattern:** - `onchain/` - Smart contracts (Solidity/Foundry)
1. Trader executes large trade moving price significantly - `kraiken-lib/` - TypeScript helper library
2. Price movement triggers recenter() function - `subgraph/base_sepolia/` - The Graph subgraph
3. Trader immediately executes reverse trade at new liquidity configuration - `services/txnBot/` - Trigger service for recentering and liquidation
4. Net result: Trader profits from predictable rebalancing, LM loses value - `onchain/analysis/` - Analysis tools and scenario testing
**Protection Mechanism - Asymmetric Slippage Profile:** *Note: Detailed technical analysis including attack vectors, VWAP algorithms, and Harberger tax implementation available in [TECHNICAL_APPENDIX.md](TECHNICAL_APPENDIX.md).*
- **ANCHOR Position**: Shallow liquidity around current price (high slippage, fast price movement)
- **FLOOR + DISCOVERY Positions**: Deep liquidity at edges (low slippage, slow price movement)
**Attack Protection Logic:**
1. First trade: Price moves quickly through shallow anchor → hits deep edge liquidity (high slippage cost)
2. Recenter: Rebalances positions around new price
3. Reverse trade: Price again moves quickly through new shallow anchor → hits opposite deep edge (high slippage cost)
4. Result: Attacker pays high slippage twice, making round-trip unprofitable
#### Position Dependencies (_set function order)
**Order:** ANCHOR → DISCOVERY → FLOOR
**Economic Rationale:**
- **ANCHOR → DISCOVERY**: Discovery amount proportional to KRAIKEN minted by anchor; positions border anchor for continuous fee capture
- **ANCHOR + DISCOVERY → FLOOR**: Floor must defend against maximum selling pressure from final circulating supply, only known after all position minting complete
- **VWAP Exclusivity**: Only FLOOR position uses VWAP for historical price memory; ANCHOR/DISCOVERY use current tick for immediate market response
### VWAPTracker.sol
- **Critical Security Component**: Provides "eternal memory" protection against dormant whale attacks
- **Dormant Whale Attack Pattern**:
1. Whale buys large amounts early at cheap prices
2. Waits for extended periods while protocol accumulates volume
3. Attempts to sell at inflated prices when market conditions are favorable
- **Protection Mechanism**: VWAP maintains historical price memory that persists through data compression
- **Compression Algorithm**: Limited to maximum 1000x compression to preserve historical significance
- **Double-Overflow Analysis**: Extensive testing shows that double-overflow scenarios requiring >1000x compression would need:
- Single transactions >10,000 ETH (unrealistic)
- Token prices >$4.3 billion (exceeds global wealth)
- Therefore, 1000x compression limit provides adequate protection against realistic scenarios
- **Floor Position Calculation**: Uses adjusted VWAP (70% base + capital inefficiency) to set floor support levels
### Stake.sol
- Staking mechanism for KRAIKEN tokens
- Collects sentiment data through staking behavior
- Provides tax rate and staking percentage data
## Deployment Addresses
### Base Sepolia
- Kraiken: `0x22c264Ecf8D4E49D1E3CabD8DD39b7C4Ab51C1B8`
- Stake: `0xe28020BCdEeAf2779dd47c670A8eFC2973316EE2`
- LP: `0x3d6a8797693a0bC598210782B6a889E11A2340Cd`
### Base Mainnet
- Kraiken: `0x45caa5929f6ee038039984205bdecf968b954820`
- Stake: `0xed70707fab05d973ad41eae8d17e2bcd36192cfc`
- LP: `0x7fd4e645ce258dd3942eddbeb2f99137da8ba13b`
## Testing Strategy
- **Unit Tests**: Individual contract functionality
- **Integration Tests**: Cross-contract interactions
- **Gas Optimization**: Use `forge snapshot` for gas tracking
- **GraphQL Tests**: Test subgraph queries and data accuracy
## Key Libraries and Dependencies
- **OpenZeppelin**: Upgradeable contracts, ERC20, access control
- **Uniswap V3**: Core liquidity provision and swapping
- **ABDK Math**: Fixed-point arithmetic operations
- **Apollo Client**: GraphQL client for subgraph data
- **Ethers.js**: Ethereum interaction library

143
TECHNICAL_APPENDIX.md Normal file
View file

@ -0,0 +1,143 @@
# Technical Appendix
This document provides detailed technical analysis and implementation details for the KRAIKEN protocol's core innovations. For high-level overview, see CLAUDE.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:**
```
FLOOR_PRICE = VWAP_PRICE * (0.7 + CAPITAL_INEFFICIENCY)
```
**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
### Optimizer Integration
**Sentiment Analysis:**
```solidity
function getLiquidityParams() returns (
uint256 capitalInefficiency,
uint256 anchorShare,
uint24 anchorWidth,
uint256 discoveryDepth
) {
// Analyze staking data to determine optimal liquidity parameters
// Higher confidence (tax rates) → more aggressive positioning
// Lower confidence → more conservative positioning
}
```
### 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 dynamic parameter adjustment
## 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
- **Optimizer.sol**: Sentiment analysis and parameter optimization
- **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
- **CLAUDE.md**: High-level overview and development guidance
- **`/onchain/analysis/README.md`**: Detailed analysis tool usage