feat: create v2-prep branch with comprehensive planning

Restructured project for V2 refactor:

**Structure Changes:**
- Moved all V1 code to orig/ folder (preserved with git mv)
- Created docs/planning/ directory
- Added orig/README_V1.md explaining V1 preservation

**Planning Documents:**
- 00_V2_MASTER_PLAN.md: Complete architecture overview
  - Executive summary of critical V1 issues
  - High-level component architecture diagrams
  - 5-phase implementation roadmap
  - Success metrics and risk mitigation

- 07_TASK_BREAKDOWN.md: Atomic task breakdown
  - 99+ hours of detailed tasks
  - Every task < 2 hours (atomic)
  - Clear dependencies and success criteria
  - Organized by implementation phase

**V2 Key Improvements:**
- Per-exchange parsers (factory pattern)
- Multi-layer strict validation
- Multi-index pool cache
- Background validation pipeline
- Comprehensive observability

**Critical Issues Addressed:**
- Zero address tokens (strict validation + cache enrichment)
- Parsing accuracy (protocol-specific parsers)
- No audit trail (background validation channel)
- Inefficient lookups (multi-index cache)
- Stats disconnection (event-driven metrics)

Next Steps:
1. Review planning documents
2. Begin Phase 1: Foundation (P1-001 through P1-010)
3. Implement parsers in Phase 2
4. Build cache system in Phase 3
5. Add validation pipeline in Phase 4
6. Migrate and test in Phase 5

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Administrator
2025-11-10 10:14:26 +01:00
parent 1773daffe7
commit 803de231ba
411 changed files with 20390 additions and 8680 deletions

View File

@@ -0,0 +1,273 @@
package exchanges
import (
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/fraktal/mev-beta/internal/logger"
"github.com/fraktal/mev-beta/pkg/math"
)
// UniswapV4PoolDetector implements PoolDetector for Uniswap V4
type UniswapV4PoolDetector struct {
client *ethclient.Client
logger *logger.Logger
config *ExchangeConfig
}
// NewUniswapV4PoolDetector creates a new Uniswap V4 pool detector
func NewUniswapV4PoolDetector(client *ethclient.Client, logger *logger.Logger, config *ExchangeConfig) *UniswapV4PoolDetector {
return &UniswapV4PoolDetector{
client: client,
logger: logger,
config: config,
}
}
// GetAllPools returns all pools containing the specified tokens
func (d *UniswapV4PoolDetector) GetAllPools(token0, token1 common.Address) ([]common.Address, error) {
// In a real implementation, this would query the Uniswap V4 hook contracts
// For now, we'll return an empty slice
return []common.Address{}, nil
}
// GetPoolForPair returns the pool address for a specific token pair
func (d *UniswapV4PoolDetector) GetPoolForPair(token0, token1 common.Address) (common.Address, error) {
// Calculate pool address using Uniswap V4 formula with hooks
// In a real implementation, this would call the pool manager
poolAddress := common.HexToAddress("0x0") // Placeholder
// For now, return empty address to indicate pool not found
return poolAddress, nil
}
// GetSupportedFeeTiers returns supported fee tiers for Uniswap V4 (varies by pool)
func (d *UniswapV4PoolDetector) GetSupportedFeeTiers() []int64 {
// Uniswap V4 pools can have different fee tiers
return []int64{100, 500, 3000, 10000} // 0.01%, 0.05%, 0.3%, 1% in basis points
}
// GetPoolType returns the pool type
func (d *UniswapV4PoolDetector) GetPoolType() string {
return "uniswap_v4_concentrated"
}
// UniswapV4LiquidityFetcher implements LiquidityFetcher for Uniswap V4
type UniswapV4LiquidityFetcher struct {
client *ethclient.Client
logger *logger.Logger
config *ExchangeConfig
engine *math.ExchangePricingEngine
}
// NewUniswapV4LiquidityFetcher creates a new Uniswap V4 liquidity fetcher
func NewUniswapV4LiquidityFetcher(client *ethclient.Client, logger *logger.Logger, config *ExchangeConfig, engine *math.ExchangePricingEngine) *UniswapV4LiquidityFetcher {
return &UniswapV4LiquidityFetcher{
client: client,
logger: logger,
config: config,
engine: engine,
}
}
// GetPoolData fetches pool information for Uniswap V4
func (f *UniswapV4LiquidityFetcher) GetPoolData(poolAddress common.Address) (*math.PoolData, error) {
// In a real implementation, this would call the pool contract to get tick, liquidity, and other data
// For now, return a placeholder pool data with Uniswap V4-specific fields
fee, err := math.NewUniversalDecimal(big.NewInt(300), 4, "FEE") // 0.3% standard fee
if err != nil {
return nil, fmt.Errorf("error creating fee decimal: %w", err)
}
reserve0Value := new(big.Int)
reserve0Value.SetString("1000000000000000000000", 10) // WETH
reserve0, err := math.NewUniversalDecimal(reserve0Value, 18, "RESERVE0")
if err != nil {
return nil, fmt.Errorf("error creating reserve0 decimal: %w", err)
}
reserve1Value := new(big.Int)
reserve1Value.SetString("1000000000000", 10) // USDC
reserve1, err := math.NewUniversalDecimal(reserve1Value, 6, "RESERVE1")
if err != nil {
return nil, fmt.Errorf("error creating reserve1 decimal: %w", err)
}
return &math.PoolData{
Address: poolAddress.Hex(),
ExchangeType: math.ExchangeUniswapV4,
Fee: fee,
Token0: math.TokenInfo{Address: "0x0", Symbol: "WETH", Decimals: 18},
Token1: math.TokenInfo{Address: "0x1", Symbol: "USDC", Decimals: 6},
Reserve0: reserve0,
Reserve1: reserve1,
SqrtPriceX96: big.NewInt(0), // Would be populated with actual sqrtPriceX96
Tick: big.NewInt(0), // Would be populated with actual tick
Liquidity: big.NewInt(0), // Would be populated with actual liquidity
}, nil
}
// GetTokenReserves fetches reserves for a specific token pair in a pool
func (f *UniswapV4LiquidityFetcher) GetTokenReserves(poolAddress, token0, token1 common.Address) (*big.Int, *big.Int, error) {
// In a real implementation, this would query the pool contract
// For now, return placeholder values
reserve0 := new(big.Int)
reserve0.SetString("1000000000000000000000", 10) // WETH
reserve1 := new(big.Int)
reserve1.SetString("1000000000000", 10) // USDC
return reserve0, reserve1, nil
}
// GetPoolPrice calculates the price of token1 in terms of token0
func (f *UniswapV4LiquidityFetcher) GetPoolPrice(poolAddress common.Address) (*big.Float, error) {
poolData, err := f.GetPoolData(poolAddress)
if err != nil {
return nil, err
}
pricer, err := f.engine.GetExchangePricer(poolData.ExchangeType)
if err != nil {
return nil, err
}
spotPrice, err := pricer.GetSpotPrice(poolData)
if err != nil {
return nil, err
}
// Convert the UniversalDecimal Value to a *big.Float
result := new(big.Float).SetInt(spotPrice.Value)
return result, nil
}
// GetLiquidityDepth calculates the liquidity depth for an amount
func (f *UniswapV4LiquidityFetcher) GetLiquidityDepth(poolAddress, tokenIn common.Address, amount *big.Int) (*big.Int, error) {
// In a real implementation, this would calculate liquidity with Uniswap V4's concentrated liquidity model
return amount, nil
}
// UniswapV4SwapRouter implements SwapRouter for Uniswap V4
type UniswapV4SwapRouter struct {
client *ethclient.Client
logger *logger.Logger
config *ExchangeConfig
engine *math.ExchangePricingEngine
}
// NewUniswapV4SwapRouter creates a new Uniswap V4 swap router
func NewUniswapV4SwapRouter(client *ethclient.Client, logger *logger.Logger, config *ExchangeConfig, engine *math.ExchangePricingEngine) *UniswapV4SwapRouter {
return &UniswapV4SwapRouter{
client: client,
logger: logger,
config: config,
engine: engine,
}
}
// CalculateSwap calculates the expected output amount for a swap
func (r *UniswapV4SwapRouter) CalculateSwap(tokenIn, tokenOut common.Address, amountIn *big.Int) (*big.Int, error) {
// Find pool for the token pair
poolAddress, err := r.findPoolForPair(tokenIn, tokenOut)
if err != nil {
return nil, fmt.Errorf("failed to find pool for pair: %w", err)
}
// Get pool data
poolData, err := r.GetPoolData(poolAddress)
if err != nil {
return nil, fmt.Errorf("failed to get pool data: %w", err)
}
// Create a UniversalDecimal from the amountIn
decimalAmountIn, err := math.NewUniversalDecimal(amountIn, 18, "AMOUNT_IN")
if err != nil {
return nil, fmt.Errorf("error creating amount in decimal: %w", err)
}
// Get the pricer
pricer, err := r.engine.GetExchangePricer(poolData.ExchangeType)
if err != nil {
return nil, err
}
// Calculate amount out using Uniswap V4's concentrated liquidity formula
amountOut, err := pricer.CalculateAmountOut(decimalAmountIn, poolData)
if err != nil {
return nil, err
}
return amountOut.Value, nil
}
// findPoolForPair finds the pool address for a given token pair
func (r *UniswapV4SwapRouter) findPoolForPair(token0, token1 common.Address) (common.Address, error) {
// In a real implementation, this would query the Uniswap V4 pool manager
// For now, return a placeholder address
return common.HexToAddress("0x0"), nil
}
// GetPoolData is a helper to fetch pool data (for internal use)
func (r *UniswapV4SwapRouter) GetPoolData(poolAddress common.Address) (*math.PoolData, error) {
fetcher := NewUniswapV4LiquidityFetcher(r.client, r.logger, r.config, r.engine)
return fetcher.GetPoolData(poolAddress)
}
// GenerateSwapData generates the calldata for a swap transaction
func (r *UniswapV4SwapRouter) GenerateSwapData(tokenIn, tokenOut common.Address, amountIn, minAmountOut *big.Int, deadline *big.Int) ([]byte, error) {
// In a real implementation, this would generate the encoded function call
// For Uniswap V4, this would typically be exactInputSingle or exactOutputSingle
return []byte{}, nil
}
// GetSwapRoute returns the route for a swap (for Uniswap V4, typically direct within a pool)
func (r *UniswapV4SwapRouter) GetSwapRoute(tokenIn, tokenOut common.Address) ([]common.Address, error) {
// For Uniswap V4, the route is usually direct within a concentrated liquidity pool
// For now, return the token pair as a direct route
return []common.Address{tokenIn, tokenOut}, nil
}
// ValidateSwap validates a swap before execution
func (r *UniswapV4SwapRouter) ValidateSwap(tokenIn, tokenOut common.Address, amountIn *big.Int) error {
if amountIn.Sign() <= 0 {
return fmt.Errorf("amountIn must be positive")
}
if tokenIn == tokenOut {
return fmt.Errorf("tokenIn and tokenOut cannot be the same")
}
if tokenIn == common.HexToAddress("0x0") || tokenOut == common.HexToAddress("0x0") {
return fmt.Errorf("invalid token addresses")
}
return nil
}
// RegisterUniswapV4WithRegistry registers Uniswap V4 implementation with the exchange registry
func RegisterUniswapV4WithRegistry(registry *ExchangeRegistry) error {
config := &ExchangeConfig{
Type: math.ExchangeUniswapV4,
Name: "Uniswap V4",
FactoryAddress: common.HexToAddress("0x000000000022D473030F116dDEE9F6B7653f39281251"), // Uniswap V4 Pool Manager (placeholder)
RouterAddress: common.HexToAddress("0x000000000022D473030F116dDEE9F6B7653f39281252"), // Uniswap V4 Router (placeholder)
PoolInitCodeHash: "0x0000000000000000000000000000000000000000000000000000000000000000", // Placeholder
SwapSelector: []byte{0x44, 0x13, 0x70, 0x64}, // exactInputSingle
StableSwapSelector: []byte{0x44, 0x13, 0x70, 0x65}, // exactOutputSingle
ChainID: 1, // Ethereum mainnet
SupportsFlashSwaps: true,
RequiresApproval: true,
MaxHops: 2,
DefaultSlippagePercent: 0.5,
Url: "https://uniswap.org",
ApiUrl: "https://api.uniswap.org",
}
registry.exchanges[math.ExchangeUniswapV4] = config
// Register the implementations as well
return nil
}