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:
268
orig/pkg/dex/sushiswap.go
Normal file
268
orig/pkg/dex/sushiswap.go
Normal file
@@ -0,0 +1,268 @@
|
||||
package dex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"github.com/ethereum/go-ethereum"
|
||||
"github.com/ethereum/go-ethereum/accounts/abi"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/ethclient"
|
||||
)
|
||||
|
||||
// SushiSwapDecoder implements DEXDecoder for SushiSwap
|
||||
type SushiSwapDecoder struct {
|
||||
*BaseDecoder
|
||||
pairABI abi.ABI
|
||||
routerABI abi.ABI
|
||||
}
|
||||
|
||||
// SushiSwap Pair ABI (minimal, compatible with UniswapV2)
|
||||
const sushiSwapPairABI = `[
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "getReserves",
|
||||
"outputs": [
|
||||
{"internalType": "uint112", "name": "reserve0", "type": "uint112"},
|
||||
{"internalType": "uint112", "name": "reserve1", "type": "uint112"},
|
||||
{"internalType": "uint32", "name": "blockTimestampLast", "type": "uint32"}
|
||||
],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "token0",
|
||||
"outputs": [{"internalType": "address", "name": "", "type": "address"}],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"constant": true,
|
||||
"inputs": [],
|
||||
"name": "token1",
|
||||
"outputs": [{"internalType": "address", "name": "", "type": "address"}],
|
||||
"payable": false,
|
||||
"stateMutability": "view",
|
||||
"type": "function"
|
||||
}
|
||||
]`
|
||||
|
||||
// SushiSwap Router ABI (minimal)
|
||||
const sushiSwapRouterABI = `[
|
||||
{
|
||||
"inputs": [
|
||||
{"internalType": "uint256", "name": "amountIn", "type": "uint256"},
|
||||
{"internalType": "uint256", "name": "amountOutMin", "type": "uint256"},
|
||||
{"internalType": "address[]", "name": "path", "type": "address[]"},
|
||||
{"internalType": "address", "name": "to", "type": "address"},
|
||||
{"internalType": "uint256", "name": "deadline", "type": "uint256"}
|
||||
],
|
||||
"name": "swapExactTokensForTokens",
|
||||
"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
},
|
||||
{
|
||||
"inputs": [
|
||||
{"internalType": "uint256", "name": "amountOut", "type": "uint256"},
|
||||
{"internalType": "uint256", "name": "amountInMax", "type": "uint256"},
|
||||
{"internalType": "address[]", "name": "path", "type": "address[]"},
|
||||
{"internalType": "address", "name": "to", "type": "address"},
|
||||
{"internalType": "uint256", "name": "deadline", "type": "uint256"}
|
||||
],
|
||||
"name": "swapTokensForExactTokens",
|
||||
"outputs": [{"internalType": "uint256[]", "name": "amounts", "type": "uint256[]"}],
|
||||
"stateMutability": "nonpayable",
|
||||
"type": "function"
|
||||
}
|
||||
]`
|
||||
|
||||
// NewSushiSwapDecoder creates a new SushiSwap decoder
|
||||
func NewSushiSwapDecoder(client *ethclient.Client) *SushiSwapDecoder {
|
||||
pairABI, _ := abi.JSON(strings.NewReader(sushiSwapPairABI))
|
||||
routerABI, _ := abi.JSON(strings.NewReader(sushiSwapRouterABI))
|
||||
|
||||
return &SushiSwapDecoder{
|
||||
BaseDecoder: NewBaseDecoder(ProtocolSushiSwap, client),
|
||||
pairABI: pairABI,
|
||||
routerABI: routerABI,
|
||||
}
|
||||
}
|
||||
|
||||
// DecodeSwap decodes a SushiSwap swap transaction
|
||||
func (d *SushiSwapDecoder) DecodeSwap(tx *types.Transaction) (*SwapInfo, error) {
|
||||
data := tx.Data()
|
||||
if len(data) < 4 {
|
||||
return nil, fmt.Errorf("transaction data too short")
|
||||
}
|
||||
|
||||
method, err := d.routerABI.MethodById(data[:4])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get method: %w", err)
|
||||
}
|
||||
|
||||
var swapInfo *SwapInfo
|
||||
|
||||
switch method.Name {
|
||||
case "swapExactTokensForTokens":
|
||||
params := make(map[string]interface{})
|
||||
if err := method.Inputs.UnpackIntoMap(params, data[4:]); err != nil {
|
||||
return nil, fmt.Errorf("failed to unpack params: %w", err)
|
||||
}
|
||||
|
||||
path := params["path"].([]common.Address)
|
||||
if len(path) < 2 {
|
||||
return nil, fmt.Errorf("invalid swap path length: %d", len(path))
|
||||
}
|
||||
|
||||
swapInfo = &SwapInfo{
|
||||
Protocol: ProtocolSushiSwap,
|
||||
TokenIn: path[0],
|
||||
TokenOut: path[len(path)-1],
|
||||
AmountIn: params["amountIn"].(*big.Int),
|
||||
AmountOut: params["amountOutMin"].(*big.Int),
|
||||
Recipient: params["to"].(common.Address),
|
||||
Deadline: params["deadline"].(*big.Int),
|
||||
Fee: big.NewInt(30), // 0.3% fee
|
||||
}
|
||||
|
||||
case "swapTokensForExactTokens":
|
||||
params := make(map[string]interface{})
|
||||
if err := method.Inputs.UnpackIntoMap(params, data[4:]); err != nil {
|
||||
return nil, fmt.Errorf("failed to unpack params: %w", err)
|
||||
}
|
||||
|
||||
path := params["path"].([]common.Address)
|
||||
if len(path) < 2 {
|
||||
return nil, fmt.Errorf("invalid swap path length: %d", len(path))
|
||||
}
|
||||
|
||||
swapInfo = &SwapInfo{
|
||||
Protocol: ProtocolSushiSwap,
|
||||
TokenIn: path[0],
|
||||
TokenOut: path[len(path)-1],
|
||||
AmountIn: params["amountInMax"].(*big.Int),
|
||||
AmountOut: params["amountOut"].(*big.Int),
|
||||
Recipient: params["to"].(common.Address),
|
||||
Deadline: params["deadline"].(*big.Int),
|
||||
Fee: big.NewInt(30), // 0.3% fee
|
||||
}
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported method: %s", method.Name)
|
||||
}
|
||||
|
||||
return swapInfo, nil
|
||||
}
|
||||
|
||||
// GetPoolReserves fetches current pool reserves for SushiSwap
|
||||
func (d *SushiSwapDecoder) GetPoolReserves(ctx context.Context, client *ethclient.Client, poolAddress common.Address) (*PoolReserves, error) {
|
||||
// Get reserves
|
||||
reservesData, err := client.CallContract(ctx, ethereum.CallMsg{
|
||||
To: &poolAddress,
|
||||
Data: d.pairABI.Methods["getReserves"].ID,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get reserves: %w", err)
|
||||
}
|
||||
|
||||
var reserves struct {
|
||||
Reserve0 *big.Int
|
||||
Reserve1 *big.Int
|
||||
BlockTimestampLast uint32
|
||||
}
|
||||
if err := d.pairABI.UnpackIntoInterface(&reserves, "getReserves", reservesData); err != nil {
|
||||
return nil, fmt.Errorf("failed to unpack reserves: %w", err)
|
||||
}
|
||||
|
||||
// Get token0
|
||||
token0Data, err := client.CallContract(ctx, ethereum.CallMsg{
|
||||
To: &poolAddress,
|
||||
Data: d.pairABI.Methods["token0"].ID,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get token0: %w", err)
|
||||
}
|
||||
token0 := common.BytesToAddress(token0Data)
|
||||
|
||||
// Get token1
|
||||
token1Data, err := client.CallContract(ctx, ethereum.CallMsg{
|
||||
To: &poolAddress,
|
||||
Data: d.pairABI.Methods["token1"].ID,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get token1: %w", err)
|
||||
}
|
||||
token1 := common.BytesToAddress(token1Data)
|
||||
|
||||
return &PoolReserves{
|
||||
Token0: token0,
|
||||
Token1: token1,
|
||||
Reserve0: reserves.Reserve0,
|
||||
Reserve1: reserves.Reserve1,
|
||||
Protocol: ProtocolSushiSwap,
|
||||
PoolAddress: poolAddress,
|
||||
Fee: big.NewInt(30), // 0.3% fee
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CalculateOutput calculates expected output for SushiSwap using constant product formula
|
||||
func (d *SushiSwapDecoder) CalculateOutput(amountIn *big.Int, reserves *PoolReserves, tokenIn common.Address) (*big.Int, error) {
|
||||
if amountIn == nil || amountIn.Sign() <= 0 {
|
||||
return nil, fmt.Errorf("invalid amountIn")
|
||||
}
|
||||
|
||||
var reserveIn, reserveOut *big.Int
|
||||
if tokenIn == reserves.Token0 {
|
||||
reserveIn = reserves.Reserve0
|
||||
reserveOut = reserves.Reserve1
|
||||
} else if tokenIn == reserves.Token1 {
|
||||
reserveIn = reserves.Reserve1
|
||||
reserveOut = reserves.Reserve0
|
||||
} else {
|
||||
return nil, fmt.Errorf("tokenIn not in pool")
|
||||
}
|
||||
|
||||
if reserveIn.Sign() == 0 || reserveOut.Sign() == 0 {
|
||||
return nil, fmt.Errorf("insufficient liquidity")
|
||||
}
|
||||
|
||||
// Constant product formula: (x + Δx * 0.997) * (y - Δy) = x * y
|
||||
// Solving for Δy: Δy = (Δx * 0.997 * y) / (x + Δx * 0.997)
|
||||
|
||||
amountInWithFee := new(big.Int).Mul(amountIn, big.NewInt(997)) // 0.3% fee = 99.7% of amount
|
||||
numerator := new(big.Int).Mul(amountInWithFee, reserveOut)
|
||||
denominator := new(big.Int).Add(
|
||||
new(big.Int).Mul(reserveIn, big.NewInt(1000)),
|
||||
amountInWithFee,
|
||||
)
|
||||
|
||||
amountOut := new(big.Int).Div(numerator, denominator)
|
||||
return amountOut, nil
|
||||
}
|
||||
|
||||
// GetQuote gets a price quote for SushiSwap
|
||||
func (d *SushiSwapDecoder) GetQuote(ctx context.Context, client *ethclient.Client, tokenIn, tokenOut common.Address, amountIn *big.Int) (*PriceQuote, error) {
|
||||
// TODO: Implement actual pool lookup via factory
|
||||
// For now, return error
|
||||
return nil, fmt.Errorf("GetQuote not yet implemented for SushiSwap")
|
||||
}
|
||||
|
||||
// IsValidPool checks if a pool is a valid SushiSwap pool
|
||||
func (d *SushiSwapDecoder) IsValidPool(ctx context.Context, client *ethclient.Client, poolAddress common.Address) (bool, error) {
|
||||
// Try to call getReserves() - if it succeeds, it's a valid pool
|
||||
_, err := client.CallContract(ctx, ethereum.CallMsg{
|
||||
To: &poolAddress,
|
||||
Data: d.pairABI.Methods["getReserves"].ID,
|
||||
}, nil)
|
||||
|
||||
return err == nil, nil
|
||||
}
|
||||
Reference in New Issue
Block a user