Files
mev-beta/orig/pkg/exchanges/uniswap_v2.go
Administrator 803de231ba 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>
2025-11-10 10:14:26 +01:00

262 lines
9.0 KiB
Go

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"
)
// UniswapV2PoolDetector implements PoolDetector for Uniswap V2
type UniswapV2PoolDetector struct {
client *ethclient.Client
logger *logger.Logger
config *ExchangeConfig
}
// NewUniswapV2PoolDetector creates a new Uniswap V2 pool detector
func NewUniswapV2PoolDetector(client *ethclient.Client, logger *logger.Logger, config *ExchangeConfig) *UniswapV2PoolDetector {
return &UniswapV2PoolDetector{
client: client,
logger: logger,
config: config,
}
}
// GetAllPools returns all pools containing the specified tokens
func (d *UniswapV2PoolDetector) GetAllPools(token0, token1 common.Address) ([]common.Address, error) {
// In a real implementation, this would query the factory contract
// For now, we'll return an empty slice
return []common.Address{}, nil
}
// GetPoolForPair returns the pool address for a specific token pair
func (d *UniswapV2PoolDetector) GetPoolForPair(token0, token1 common.Address) (common.Address, error) {
// Calculate pool address using Uniswap V2 factory formula
// In a real implementation, this would call the factory's getPair function
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 V2 (standard 0.3%)
func (d *UniswapV2PoolDetector) GetSupportedFeeTiers() []int64 {
return []int64{3000} // 0.3% in basis points
}
// GetPoolType returns the pool type
func (d *UniswapV2PoolDetector) GetPoolType() string {
return "uniswap_v2_constant_product"
}
// UniswapV2LiquidityFetcher implements LiquidityFetcher for Uniswap V2
type UniswapV2LiquidityFetcher struct {
client *ethclient.Client
logger *logger.Logger
config *ExchangeConfig
engine *math.ExchangePricingEngine
}
// NewUniswapV2LiquidityFetcher creates a new Uniswap V2 liquidity fetcher
func NewUniswapV2LiquidityFetcher(client *ethclient.Client, logger *logger.Logger, config *ExchangeConfig, engine *math.ExchangePricingEngine) *UniswapV2LiquidityFetcher {
return &UniswapV2LiquidityFetcher{
client: client,
logger: logger,
config: config,
engine: engine,
}
}
// GetPoolData fetches pool information for Uniswap V2
func (f *UniswapV2LiquidityFetcher) GetPoolData(poolAddress common.Address) (*math.PoolData, error) {
// In a real implementation, this would call the pool contract to get reserves
// For now, return a placeholder pool data
fee, err := math.NewUniversalDecimal(big.NewInt(300), 4, "FEE") // 0.3%
if err != nil {
return nil, fmt.Errorf("error creating fee decimal: %w", err)
}
reserve0, err := math.NewUniversalDecimal(big.NewInt(1000000), 18, "RESERVE0")
if err != nil {
return nil, fmt.Errorf("error creating reserve0 decimal: %w", err)
}
reserve1, err := math.NewUniversalDecimal(big.NewInt(1000000), 18, "RESERVE1")
if err != nil {
return nil, fmt.Errorf("error creating reserve1 decimal: %w", err)
}
return &math.PoolData{
Address: poolAddress.Hex(),
ExchangeType: math.ExchangeUniswapV2,
Fee: fee,
Token0: math.TokenInfo{Address: "0x0", Symbol: "TOKEN0", Decimals: 18},
Token1: math.TokenInfo{Address: "0x1", Symbol: "TOKEN1", Decimals: 18},
Reserve0: reserve0,
Reserve1: reserve1,
}, nil
}
// GetTokenReserves fetches reserves for a specific token pair in a pool
func (f *UniswapV2LiquidityFetcher) 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
return big.NewInt(1000000), big.NewInt(1000000), nil
}
// GetPoolPrice calculates the price of token1 in terms of token0
func (f *UniswapV2LiquidityFetcher) 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 *UniswapV2LiquidityFetcher) GetLiquidityDepth(poolAddress, tokenIn common.Address, amount *big.Int) (*big.Int, error) {
// In a real implementation, this would calculate how much of the token
// can be swapped before the price impact becomes too large
return amount, nil
}
// UniswapV2SwapRouter implements SwapRouter for Uniswap V2
type UniswapV2SwapRouter struct {
client *ethclient.Client
logger *logger.Logger
config *ExchangeConfig
engine *math.ExchangePricingEngine
}
// NewUniswapV2SwapRouter creates a new Uniswap V2 swap router
func NewUniswapV2SwapRouter(client *ethclient.Client, logger *logger.Logger, config *ExchangeConfig, engine *math.ExchangePricingEngine) *UniswapV2SwapRouter {
return &UniswapV2SwapRouter{
client: client,
logger: logger,
config: config,
engine: engine,
}
}
// CalculateSwap calculates the expected output amount for a swap
func (r *UniswapV2SwapRouter) 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
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 *UniswapV2SwapRouter) findPoolForPair(token0, token1 common.Address) (common.Address, error) {
// In a real implementation, this would query the factory contract
// For now, return a placeholder address
return common.HexToAddress("0x0"), nil
}
// GetPoolData is a helper to fetch pool data (for internal use)
func (r *UniswapV2SwapRouter) GetPoolData(poolAddress common.Address) (*math.PoolData, error) {
fetcher := NewUniswapV2LiquidityFetcher(r.client, r.logger, r.config, r.engine)
return fetcher.GetPoolData(poolAddress)
}
// GenerateSwapData generates the calldata for a swap transaction
func (r *UniswapV2SwapRouter) 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 V2, this would typically be swapExactTokensForTokens
return []byte{}, nil
}
// GetSwapRoute returns the route for a swap (for Uniswap V2, this is typically direct)
func (r *UniswapV2SwapRouter) GetSwapRoute(tokenIn, tokenOut common.Address) ([]common.Address, error) {
// Uniswap V2 typically requires a direct swap
return []common.Address{tokenIn, tokenOut}, nil
}
// ValidateSwap validates a swap before execution
func (r *UniswapV2SwapRouter) 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
}
// RegisterUniswapV2WithRegistry registers Uniswap V2 implementation with the exchange registry
func RegisterUniswapV2WithRegistry(registry *ExchangeRegistry) error {
config := &ExchangeConfig{
Type: math.ExchangeUniswapV2,
Name: "Uniswap V2",
FactoryAddress: common.HexToAddress("0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"), // Uniswap V2 Factory on mainnet
RouterAddress: common.HexToAddress("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"), // Uniswap V2 Router on mainnet
PoolInitCodeHash: "0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f",
SwapSelector: []byte{0x18, 0x2d, 0x2e, 0xdb}, // swapExactTokensForTokens
StableSwapSelector: []byte{},
ChainID: 1, // Ethereum mainnet
SupportsFlashSwaps: true,
RequiresApproval: true,
MaxHops: 3,
DefaultSlippagePercent: 0.5,
Url: "https://uniswap.org",
ApiUrl: "https://api.uniswap.org",
}
registry.exchanges[math.ExchangeUniswapV2] = config
// Register the implementations as well
return nil
}