refactor: move all remaining files to orig/ directory
Completed clean root directory structure: - Root now contains only: .git, .env, docs/, orig/ - Moved all remaining files and directories to orig/: - Config files (.claude, .dockerignore, .drone.yml, etc.) - All .env variants (except active .env) - Git config (.gitconfig, .github, .gitignore, etc.) - Tool configs (.golangci.yml, .revive.toml, etc.) - Documentation (*.md files, @prompts) - Build files (Dockerfiles, Makefile, go.mod, go.sum) - Docker compose files - All source directories (scripts, tests, tools, etc.) - Runtime directories (logs, monitoring, reports) - Dependency files (node_modules, lib, cache) - Special files (--delete) - Removed empty runtime directories (bin/, data/) V2 structure is now clean: - docs/planning/ - V2 planning documents - orig/ - Complete V1 codebase preserved - .env - Active environment config (not in git) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
7
orig/tools/audit-orchestrator/go.mod
Normal file
7
orig/tools/audit-orchestrator/go.mod
Normal file
@@ -0,0 +1,7 @@
|
||||
module github.com/fraktal/mev-beta/tools/audit-orchestrator
|
||||
|
||||
go 1.24
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../../
|
||||
|
||||
require github.com/fraktal/mev-beta v0.0.0-00010101000000-000000000000
|
||||
2103
orig/tools/audit-orchestrator/internal/orchestrator.go
Normal file
2103
orig/tools/audit-orchestrator/internal/orchestrator.go
Normal file
File diff suppressed because it is too large
Load Diff
95
orig/tools/audit-orchestrator/main.go
Normal file
95
orig/tools/audit-orchestrator/main.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/audit-orchestrator/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
mode = flag.String("mode", "comprehensive", "Audit mode: quick, standard, comprehensive, continuous, custom")
|
||||
configFile = flag.String("config", "orchestrator-config.yaml", "Configuration file path")
|
||||
outputDir = flag.String("output", "reports/orchestrator", "Output directory")
|
||||
verbose = flag.Bool("verbose", false, "Enable verbose output")
|
||||
dryRun = flag.Bool("dry-run", false, "Perform dry run without executing audits")
|
||||
parallel = flag.Bool("parallel", true, "Run compatible audits in parallel")
|
||||
timeout = flag.Duration("timeout", 60*time.Minute, "Overall timeout for all audits")
|
||||
reportFormat = flag.String("format", "html", "Report format: html, json, pdf, all")
|
||||
dashboardMode = flag.Bool("dashboard", false, "Start interactive dashboard")
|
||||
watchMode = flag.Bool("watch", false, "Continuous monitoring mode")
|
||||
webhookURL = flag.String("webhook", "", "Webhook URL for notifications")
|
||||
schedule = flag.String("schedule", "", "Cron schedule for automatic runs")
|
||||
baselineDir = flag.String("baseline", "", "Baseline reports directory for comparison")
|
||||
thresholds = flag.String("thresholds", "", "Custom quality thresholds file")
|
||||
environment = flag.String("env", "development", "Environment: development, staging, production")
|
||||
integrationMode = flag.Bool("integration", false, "Integration with external systems")
|
||||
metricsExport = flag.Bool("metrics", false, "Export metrics to external systems")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
// Create output directory
|
||||
if err := os.MkdirAll(*outputDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Initialize audit orchestrator
|
||||
orchestrator, err := internal.NewAuditOrchestrator(&internal.OrchestratorConfig{
|
||||
Mode: *mode,
|
||||
ConfigFile: *configFile,
|
||||
OutputDir: *outputDir,
|
||||
Verbose: *verbose,
|
||||
DryRun: *dryRun,
|
||||
Parallel: *parallel,
|
||||
Timeout: *timeout,
|
||||
ReportFormat: *reportFormat,
|
||||
DashboardMode: *dashboardMode,
|
||||
WatchMode: *watchMode,
|
||||
WebhookURL: *webhookURL,
|
||||
Schedule: *schedule,
|
||||
BaselineDir: *baselineDir,
|
||||
Thresholds: *thresholds,
|
||||
Environment: *environment,
|
||||
IntegrationMode: *integrationMode,
|
||||
MetricsExport: *metricsExport,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize audit orchestrator: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, *timeout)
|
||||
defer cancel()
|
||||
|
||||
if *dashboardMode {
|
||||
fmt.Println("Starting audit orchestrator dashboard...")
|
||||
if err := orchestrator.StartDashboard(ctx); err != nil {
|
||||
log.Fatalf("Dashboard failed: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if *watchMode {
|
||||
fmt.Println("Starting continuous monitoring mode...")
|
||||
if err := orchestrator.StartContinuousMonitoring(ctx); err != nil {
|
||||
log.Fatalf("Continuous monitoring failed: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Starting audit orchestration in %s mode...\n", *mode)
|
||||
exitCode, err := orchestrator.RunOrchestration(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("Audit orchestration failed: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Audit orchestration complete. Reports saved to: %s\n", *outputDir)
|
||||
fmt.Printf("Exit code: %d\n", exitCode)
|
||||
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
175
orig/tools/bridge/ci_agent_bridge.go
Normal file
175
orig/tools/bridge/ci_agent_bridge.go
Normal file
@@ -0,0 +1,175 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"archive/zip"
|
||||
)
|
||||
|
||||
// SummarizeResult holds artifact summary data
|
||||
type SummarizeResult struct {
|
||||
Files []string `json:"files"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// SummarizeConfig configures summarization behavior
|
||||
type SummarizeConfig struct {
|
||||
ArtifactsDir string
|
||||
OutputFile string
|
||||
}
|
||||
|
||||
// ApplyPatch applies a patch file to a new branch
|
||||
func ApplyPatch(op PatchOperation) error {
|
||||
if op.PatchFile == "" || op.BranchName == "" {
|
||||
return fmt.Errorf("both --patch and --branch are required")
|
||||
}
|
||||
|
||||
// create new branch
|
||||
cmd := exec.Command("git", "checkout", "-b", op.BranchName)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("git checkout failed: %s: %w", string(out), err)
|
||||
}
|
||||
|
||||
// apply patch
|
||||
cmd = exec.Command("git", "apply", op.PatchFile)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("git apply failed: %s: %w", string(out), err)
|
||||
}
|
||||
|
||||
log.Printf("[CI-Agent-Bridge] Patch applied to branch: %s", op.BranchName)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevertBranch deletes a branch (hard reset)
|
||||
func RevertBranch(branch string) error {
|
||||
if branch == "" {
|
||||
return fmt.Errorf("--branch is required")
|
||||
}
|
||||
|
||||
// switch to main first
|
||||
cmd := exec.Command("git", "checkout", "main")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("git checkout main failed: %s: %w", string(out), err)
|
||||
}
|
||||
|
||||
// delete branch
|
||||
cmd = exec.Command("git", "branch", "-D", branch)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("git branch delete failed: %s: %w", string(out), err)
|
||||
}
|
||||
|
||||
log.Printf("[CI-Agent-Bridge] Branch reverted: %s", branch)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunPodmanCompose executes podman-compose up
|
||||
func RunPodmanCompose() error {
|
||||
log.Println("[CI-Agent-Bridge] Starting podman-compose...")
|
||||
cmd := exec.Command("podman-compose", "up", "-d")
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
// ZipDir compresses a directory into a ZIP archive
|
||||
func ZipDir(srcDir, destZip string) error {
|
||||
zipFile, err := os.Create(destZip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer zipFile.Close()
|
||||
|
||||
archive := zip.NewWriter(zipFile)
|
||||
defer archive.Close()
|
||||
|
||||
return filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// skip directories
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// create file in archive
|
||||
relPath, _ := filepath.Rel(srcDir, path)
|
||||
zipEntry, err := archive.Create(relPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// copy file data
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(zipEntry, file)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// SummarizeArtifacts creates a JSON summary and ZIP of artifacts
|
||||
func SummarizeArtifacts(cfg SummarizeConfig) error {
|
||||
var files []string
|
||||
err := filepath.Walk(cfg.ArtifactsDir, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
relPath, _ := filepath.Rel(cfg.ArtifactsDir, path)
|
||||
files = append(files, relPath)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to walk artifacts dir: %w", err)
|
||||
}
|
||||
|
||||
result := SummarizeResult{
|
||||
Files: files,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
// write JSON summary
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
if err := os.WriteFile(cfg.OutputFile, data, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write summary: %w", err)
|
||||
}
|
||||
|
||||
// create ZIP of artifacts
|
||||
zipPath := strings.TrimSuffix(cfg.OutputFile, filepath.Ext(cfg.OutputFile)) + ".zip"
|
||||
if err := ZipDir(cfg.ArtifactsDir, zipPath); err != nil {
|
||||
return fmt.Errorf("failed to create zip: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[CI-Agent-Bridge] Artifacts summarized to %s (%d files)", cfg.OutputFile, len(files))
|
||||
return nil
|
||||
}
|
||||
|
||||
// PatchOperation holds patch application parameters
|
||||
type PatchOperation struct {
|
||||
PatchFile string
|
||||
BranchName string
|
||||
}
|
||||
|
||||
// generateSecureBranchName creates a cryptographically secure random branch name
|
||||
func generateSecureBranchName() (string, error) {
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "ai/" + hex.EncodeToString(bytes), nil
|
||||
}
|
||||
7
orig/tools/cicd-audit/go.mod
Normal file
7
orig/tools/cicd-audit/go.mod
Normal file
@@ -0,0 +1,7 @@
|
||||
module github.com/fraktal/mev-beta/tools/cicd-audit
|
||||
|
||||
go 1.24
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../../
|
||||
|
||||
require github.com/fraktal/mev-beta v0.0.0-00010101000000-000000000000
|
||||
1478
orig/tools/cicd-audit/internal/cicd_auditor.go
Normal file
1478
orig/tools/cicd-audit/internal/cicd_auditor.go
Normal file
File diff suppressed because it is too large
Load Diff
75
orig/tools/cicd-audit/main.go
Normal file
75
orig/tools/cicd-audit/main.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/cicd-audit/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
pipeline = flag.String("pipeline", "full", "Pipeline type: quick, standard, full, custom")
|
||||
configFile = flag.String("config", "audit-config.yaml", "Configuration file path")
|
||||
outputDir = flag.String("output", "reports/cicd-audit", "Output directory")
|
||||
verbose = flag.Bool("verbose", false, "Enable verbose output")
|
||||
parallel = flag.Bool("parallel", true, "Run audits in parallel")
|
||||
failFast = flag.Bool("fail-fast", false, "Stop on first failure")
|
||||
reportFormat = flag.String("format", "junit", "Report format: junit, json, html, all")
|
||||
timeout = flag.Duration("timeout", 30*time.Minute, "Overall timeout for all audits")
|
||||
stage = flag.String("stage", "all", "CI/CD stage: build, test, security, deploy, all")
|
||||
environment = flag.String("env", "development", "Environment: development, staging, production")
|
||||
slackWebhook = flag.String("slack-webhook", "", "Slack webhook URL for notifications")
|
||||
emailRecipients = flag.String("email", "", "Comma-separated email recipients for notifications")
|
||||
baselineMode = flag.Bool("baseline", false, "Generate baseline reports")
|
||||
compareMode = flag.Bool("compare", false, "Compare against baseline")
|
||||
metricsMode = flag.Bool("metrics", false, "Generate metrics and trends")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
// Create output directory
|
||||
if err := os.MkdirAll(*outputDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Initialize CI/CD auditor
|
||||
auditor, err := internal.NewCICDAuditor(&internal.CICDAuditConfig{
|
||||
Pipeline: *pipeline,
|
||||
ConfigFile: *configFile,
|
||||
OutputDir: *outputDir,
|
||||
Verbose: *verbose,
|
||||
Parallel: *parallel,
|
||||
FailFast: *failFast,
|
||||
ReportFormat: *reportFormat,
|
||||
Timeout: *timeout,
|
||||
Stage: *stage,
|
||||
Environment: *environment,
|
||||
SlackWebhook: *slackWebhook,
|
||||
EmailRecipients: *emailRecipients,
|
||||
BaselineMode: *baselineMode,
|
||||
CompareMode: *compareMode,
|
||||
MetricsMode: *metricsMode,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize CI/CD auditor: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, *timeout)
|
||||
defer cancel()
|
||||
|
||||
fmt.Printf("Starting CI/CD audit pipeline: %s...\n", *pipeline)
|
||||
exitCode, err := auditor.RunCICDPipeline(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("CI/CD audit pipeline failed: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("CI/CD audit pipeline complete. Reports saved to: %s\n", *outputDir)
|
||||
fmt.Printf("Exit code: %d\n", exitCode)
|
||||
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
7
orig/tools/exchange-audit/go.mod
Normal file
7
orig/tools/exchange-audit/go.mod
Normal file
@@ -0,0 +1,7 @@
|
||||
module github.com/fraktal/mev-beta/tools/exchange-audit
|
||||
|
||||
go 1.24
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../../
|
||||
|
||||
require github.com/fraktal/mev-beta v0.0.0-00010101000000-000000000000
|
||||
816
orig/tools/exchange-audit/internal/exchange_auditor.go
Normal file
816
orig/tools/exchange-audit/internal/exchange_auditor.go
Normal file
@@ -0,0 +1,816 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ExchangeAuditConfig struct {
|
||||
Exchanges string
|
||||
Network string
|
||||
OutputDir string
|
||||
Verbose bool
|
||||
DeepCheck bool
|
||||
CheckConnectivity bool
|
||||
CheckContracts bool
|
||||
CheckAPIs bool
|
||||
CheckIntegration bool
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
type ExchangeAuditor struct {
|
||||
config *ExchangeAuditConfig
|
||||
supportedExchanges []string
|
||||
results *AuditResults
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type AuditResults struct {
|
||||
NetworkAudited string `json:"network_audited"`
|
||||
TotalExchanges int `json:"total_exchanges"`
|
||||
PassedExchanges int `json:"passed_exchanges"`
|
||||
FailedExchanges int `json:"failed_exchanges"`
|
||||
ExchangeResults []ExchangeAuditResult `json:"exchange_results"`
|
||||
OverallScore float64 `json:"overall_score"`
|
||||
CriticalIssues []CriticalIssue `json:"critical_issues"`
|
||||
RecommendedActions []string `json:"recommended_actions"`
|
||||
AuditSummary AuditSummary `json:"audit_summary"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
DurationMs int64 `json:"duration_ms"`
|
||||
}
|
||||
|
||||
type ExchangeAuditResult struct {
|
||||
Exchange string `json:"exchange"`
|
||||
OverallStatus string `json:"overall_status"`
|
||||
Score float64 `json:"score"`
|
||||
ConnectivityCheck CheckResult `json:"connectivity_check"`
|
||||
ContractCheck CheckResult `json:"contract_check"`
|
||||
APICheck CheckResult `json:"api_check"`
|
||||
IntegrationCheck CheckResult `json:"integration_check"`
|
||||
SpecificChecks map[string]CheckResult `json:"specific_checks"`
|
||||
Issues []AuditIssue `json:"issues"`
|
||||
Recommendations []string `json:"recommendations"`
|
||||
LastUpdated time.Time `json:"last_updated"`
|
||||
}
|
||||
|
||||
type CheckResult struct {
|
||||
Status string `json:"status"`
|
||||
Passed bool `json:"passed"`
|
||||
Score float64 `json:"score"`
|
||||
Details string `json:"details"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Duration int64 `json:"duration_ms"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type AuditIssue struct {
|
||||
Severity string `json:"severity"`
|
||||
Category string `json:"category"`
|
||||
Description string `json:"description"`
|
||||
Exchange string `json:"exchange"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Suggestion string `json:"suggestion,omitempty"`
|
||||
}
|
||||
|
||||
type CriticalIssue struct {
|
||||
Exchange string `json:"exchange"`
|
||||
Issue string `json:"issue"`
|
||||
Impact string `json:"impact"`
|
||||
Severity string `json:"severity"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
type AuditSummary struct {
|
||||
ConnectivityScore float64 `json:"connectivity_score"`
|
||||
ContractScore float64 `json:"contract_score"`
|
||||
APIScore float64 `json:"api_score"`
|
||||
IntegrationScore float64 `json:"integration_score"`
|
||||
TotalChecks int `json:"total_checks"`
|
||||
PassedChecks int `json:"passed_checks"`
|
||||
FailedChecks int `json:"failed_checks"`
|
||||
}
|
||||
|
||||
func NewExchangeAuditor(config *ExchangeAuditConfig) (*ExchangeAuditor, error) {
|
||||
// Parse supported exchanges
|
||||
exchanges := strings.Split(config.Exchanges, ",")
|
||||
for i, exchange := range exchanges {
|
||||
exchanges[i] = strings.TrimSpace(exchange)
|
||||
}
|
||||
|
||||
// Create HTTP client with timeout
|
||||
httpClient := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
return &ExchangeAuditor{
|
||||
config: config,
|
||||
supportedExchanges: exchanges,
|
||||
httpClient: httpClient,
|
||||
results: &AuditResults{
|
||||
NetworkAudited: config.Network,
|
||||
ExchangeResults: make([]ExchangeAuditResult, 0),
|
||||
CriticalIssues: make([]CriticalIssue, 0),
|
||||
RecommendedActions: make([]string, 0),
|
||||
Timestamp: time.Now(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) AuditExchanges(ctx context.Context) error {
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
ea.results.DurationMs = time.Since(startTime).Milliseconds()
|
||||
}()
|
||||
|
||||
ea.results.TotalExchanges = len(ea.supportedExchanges)
|
||||
|
||||
for _, exchange := range ea.supportedExchanges {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
if ea.config.Verbose {
|
||||
fmt.Printf("Auditing exchange: %s\n", exchange)
|
||||
}
|
||||
|
||||
result := ea.auditSingleExchange(ctx, exchange)
|
||||
ea.results.ExchangeResults = append(ea.results.ExchangeResults, result)
|
||||
|
||||
if result.OverallStatus == "PASS" {
|
||||
ea.results.PassedExchanges++
|
||||
} else {
|
||||
ea.results.FailedExchanges++
|
||||
}
|
||||
|
||||
// Check for critical issues
|
||||
for _, issue := range result.Issues {
|
||||
if issue.Severity == "CRITICAL" {
|
||||
ea.results.CriticalIssues = append(ea.results.CriticalIssues, CriticalIssue{
|
||||
Exchange: exchange,
|
||||
Issue: issue.Description,
|
||||
Impact: "Exchange integration failure",
|
||||
Severity: issue.Severity,
|
||||
Timestamp: time.Now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ea.calculateOverallScore()
|
||||
ea.generateRecommendations()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) auditSingleExchange(ctx context.Context, exchange string) ExchangeAuditResult {
|
||||
result := ExchangeAuditResult{
|
||||
Exchange: exchange,
|
||||
SpecificChecks: make(map[string]CheckResult),
|
||||
Issues: make([]AuditIssue, 0),
|
||||
Recommendations: make([]string, 0),
|
||||
LastUpdated: time.Now(),
|
||||
}
|
||||
|
||||
var totalScore float64
|
||||
var checkCount int
|
||||
|
||||
// Connectivity check
|
||||
if ea.config.CheckConnectivity {
|
||||
result.ConnectivityCheck = ea.checkConnectivity(ctx, exchange)
|
||||
totalScore += result.ConnectivityCheck.Score
|
||||
checkCount++
|
||||
}
|
||||
|
||||
// Contract validation check
|
||||
if ea.config.CheckContracts {
|
||||
result.ContractCheck = ea.checkContracts(ctx, exchange)
|
||||
totalScore += result.ContractCheck.Score
|
||||
checkCount++
|
||||
}
|
||||
|
||||
// API endpoint check
|
||||
if ea.config.CheckAPIs {
|
||||
result.APICheck = ea.checkAPIs(ctx, exchange)
|
||||
totalScore += result.APICheck.Score
|
||||
checkCount++
|
||||
}
|
||||
|
||||
// Integration completeness check
|
||||
if ea.config.CheckIntegration {
|
||||
result.IntegrationCheck = ea.checkIntegration(ctx, exchange)
|
||||
totalScore += result.IntegrationCheck.Score
|
||||
checkCount++
|
||||
}
|
||||
|
||||
// Exchange-specific checks
|
||||
ea.performExchangeSpecificChecks(ctx, exchange, &result)
|
||||
|
||||
// Calculate overall score
|
||||
if checkCount > 0 {
|
||||
result.Score = totalScore / float64(checkCount)
|
||||
}
|
||||
|
||||
// Determine overall status
|
||||
if result.Score >= 80.0 {
|
||||
result.OverallStatus = "PASS"
|
||||
} else if result.Score >= 60.0 {
|
||||
result.OverallStatus = "WARNING"
|
||||
} else {
|
||||
result.OverallStatus = "FAIL"
|
||||
}
|
||||
|
||||
// Generate exchange-specific recommendations
|
||||
ea.generateExchangeRecommendations(exchange, &result)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkConnectivity(ctx context.Context, exchange string) CheckResult {
|
||||
startTime := time.Now()
|
||||
result := CheckResult{
|
||||
Timestamp: startTime,
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
defer func() {
|
||||
result.Duration = time.Since(startTime).Milliseconds()
|
||||
}()
|
||||
|
||||
switch exchange {
|
||||
case "uniswap_v2", "uniswap_v3":
|
||||
return ea.checkUniswapConnectivity(ctx, exchange)
|
||||
case "curve":
|
||||
return ea.checkCurveConnectivity(ctx, exchange)
|
||||
case "balancer":
|
||||
return ea.checkBalancerConnectivity(ctx, exchange)
|
||||
default:
|
||||
result.Status = "UNSUPPORTED"
|
||||
result.Passed = false
|
||||
result.Score = 0.0
|
||||
result.Details = fmt.Sprintf("Exchange %s not supported for connectivity check", exchange)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkUniswapConnectivity(ctx context.Context, exchange string) CheckResult {
|
||||
result := CheckResult{
|
||||
Timestamp: time.Now(),
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// Test connection to Uniswap contracts
|
||||
// This would normally test actual RPC connectivity
|
||||
success := true // Simplified for demo
|
||||
|
||||
if success {
|
||||
result.Status = "CONNECTED"
|
||||
result.Passed = true
|
||||
result.Score = 100.0
|
||||
result.Details = fmt.Sprintf("%s connectivity verified", exchange)
|
||||
result.Metadata["rpc_latency_ms"] = 150
|
||||
result.Metadata["block_height"] = 12345678
|
||||
} else {
|
||||
result.Status = "DISCONNECTED"
|
||||
result.Passed = false
|
||||
result.Score = 0.0
|
||||
result.Details = fmt.Sprintf("Failed to connect to %s", exchange)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkCurveConnectivity(ctx context.Context, exchange string) CheckResult {
|
||||
result := CheckResult{
|
||||
Timestamp: time.Now(),
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// Simplified connectivity check for Curve
|
||||
result.Status = "CONNECTED"
|
||||
result.Passed = true
|
||||
result.Score = 95.0
|
||||
result.Details = "Curve connectivity verified with minor latency"
|
||||
result.Metadata["pool_count"] = 45
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkBalancerConnectivity(ctx context.Context, exchange string) CheckResult {
|
||||
result := CheckResult{
|
||||
Timestamp: time.Now(),
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// Simplified connectivity check for Balancer
|
||||
result.Status = "CONNECTED"
|
||||
result.Passed = true
|
||||
result.Score = 90.0
|
||||
result.Details = "Balancer connectivity verified"
|
||||
result.Metadata["vault_address"] = "0xBA12222222228d8Ba445958a75a0704d566BF2C8"
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkContracts(ctx context.Context, exchange string) CheckResult {
|
||||
result := CheckResult{
|
||||
Timestamp: time.Now(),
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// Contract validation logic
|
||||
contractAddresses := ea.getExpectedContractAddresses(exchange)
|
||||
validContracts := 0
|
||||
totalContracts := len(contractAddresses)
|
||||
|
||||
for contractName, address := range contractAddresses {
|
||||
if ea.validateContractAddress(ctx, address) {
|
||||
validContracts++
|
||||
result.Metadata[contractName] = "VALID"
|
||||
} else {
|
||||
result.Metadata[contractName] = "INVALID"
|
||||
}
|
||||
}
|
||||
|
||||
if totalContracts > 0 {
|
||||
result.Score = float64(validContracts) / float64(totalContracts) * 100.0
|
||||
result.Passed = result.Score >= 80.0
|
||||
}
|
||||
|
||||
if result.Passed {
|
||||
result.Status = "VALID_CONTRACTS"
|
||||
result.Details = fmt.Sprintf("All %d contracts validated for %s", validContracts, exchange)
|
||||
} else {
|
||||
result.Status = "INVALID_CONTRACTS"
|
||||
result.Details = fmt.Sprintf("Only %d/%d contracts valid for %s", validContracts, totalContracts, exchange)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) getExpectedContractAddresses(exchange string) map[string]string {
|
||||
// Return expected contract addresses for each exchange on the target network
|
||||
contracts := make(map[string]string)
|
||||
|
||||
switch exchange {
|
||||
case "uniswap_v2":
|
||||
contracts["factory"] = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"
|
||||
contracts["router"] = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
|
||||
case "uniswap_v3":
|
||||
contracts["factory"] = "0x1F98431c8aD98523631AE4a59f267346ea31F984"
|
||||
contracts["router"] = "0xE592427A0AEce92De3Edee1F18E0157C05861564"
|
||||
contracts["quoter"] = "0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6"
|
||||
case "curve":
|
||||
contracts["registry"] = "0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5"
|
||||
contracts["factory"] = "0x0959158b6040D32d04c301A72CBFD6b39E21c9AE"
|
||||
case "balancer":
|
||||
contracts["vault"] = "0xBA12222222228d8Ba445958a75a0704d566BF2C8"
|
||||
contracts["factory"] = "0x8E9aa87E45f19D9e0FA1051c10e0DB79c9a08a08"
|
||||
}
|
||||
|
||||
return contracts
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) validateContractAddress(ctx context.Context, address string) bool {
|
||||
// Simplified contract validation
|
||||
// In reality, this would check if the address contains valid contract bytecode
|
||||
return len(address) == 42 && strings.HasPrefix(address, "0x")
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkAPIs(ctx context.Context, exchange string) CheckResult {
|
||||
result := CheckResult{
|
||||
Timestamp: time.Now(),
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
apiEndpoints := ea.getAPIEndpoints(exchange)
|
||||
successfulAPIs := 0
|
||||
totalAPIs := len(apiEndpoints)
|
||||
|
||||
for endpoint, url := range apiEndpoints {
|
||||
if ea.testAPIEndpoint(ctx, url) {
|
||||
successfulAPIs++
|
||||
result.Metadata[endpoint] = "ACCESSIBLE"
|
||||
} else {
|
||||
result.Metadata[endpoint] = "FAILED"
|
||||
}
|
||||
}
|
||||
|
||||
if totalAPIs > 0 {
|
||||
result.Score = float64(successfulAPIs) / float64(totalAPIs) * 100.0
|
||||
result.Passed = result.Score >= 70.0
|
||||
}
|
||||
|
||||
if result.Passed {
|
||||
result.Status = "API_ACCESSIBLE"
|
||||
result.Details = fmt.Sprintf("All %d APIs accessible for %s", successfulAPIs, exchange)
|
||||
} else {
|
||||
result.Status = "API_ISSUES"
|
||||
result.Details = fmt.Sprintf("Only %d/%d APIs accessible for %s", successfulAPIs, totalAPIs, exchange)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) getAPIEndpoints(exchange string) map[string]string {
|
||||
endpoints := make(map[string]string)
|
||||
|
||||
switch exchange {
|
||||
case "uniswap_v2", "uniswap_v3":
|
||||
endpoints["subgraph"] = "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3"
|
||||
endpoints["info_api"] = "https://api.uniswap.org/v1/pools"
|
||||
case "curve":
|
||||
endpoints["api"] = "https://api.curve.fi/api/getPools/all"
|
||||
endpoints["subgraph"] = "https://api.thegraph.com/subgraphs/name/messari/curve-finance-ethereum"
|
||||
case "balancer":
|
||||
endpoints["api"] = "https://api.balancer.fi/pools"
|
||||
endpoints["subgraph"] = "https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-v2"
|
||||
}
|
||||
|
||||
return endpoints
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) testAPIEndpoint(ctx context.Context, url string) bool {
|
||||
// Simplified API test - just check if endpoint responds
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
resp, err := ea.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return resp.StatusCode == 200
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkIntegration(ctx context.Context, exchange string) CheckResult {
|
||||
result := CheckResult{
|
||||
Timestamp: time.Now(),
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// Check integration completeness
|
||||
integrationChecks := ea.getIntegrationChecks(exchange)
|
||||
passedChecks := 0
|
||||
totalChecks := len(integrationChecks)
|
||||
|
||||
for checkName, passed := range integrationChecks {
|
||||
if passed {
|
||||
passedChecks++
|
||||
result.Metadata[checkName] = "PASS"
|
||||
} else {
|
||||
result.Metadata[checkName] = "FAIL"
|
||||
}
|
||||
}
|
||||
|
||||
if totalChecks > 0 {
|
||||
result.Score = float64(passedChecks) / float64(totalChecks) * 100.0
|
||||
result.Passed = result.Score >= 80.0
|
||||
}
|
||||
|
||||
if result.Passed {
|
||||
result.Status = "FULLY_INTEGRATED"
|
||||
result.Details = fmt.Sprintf("All %d integration checks passed for %s", passedChecks, exchange)
|
||||
} else {
|
||||
result.Status = "PARTIAL_INTEGRATION"
|
||||
result.Details = fmt.Sprintf("Only %d/%d integration checks passed for %s", passedChecks, totalChecks, exchange)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) getIntegrationChecks(exchange string) map[string]bool {
|
||||
checks := make(map[string]bool)
|
||||
|
||||
// Common integration checks
|
||||
checks["price_fetching"] = true
|
||||
checks["liquidity_calculation"] = true
|
||||
checks["swap_simulation"] = true
|
||||
checks["gas_estimation"] = true
|
||||
|
||||
// Exchange-specific checks
|
||||
switch exchange {
|
||||
case "uniswap_v2":
|
||||
checks["pair_discovery"] = true
|
||||
checks["reserve_calculation"] = true
|
||||
checks["fee_calculation"] = true
|
||||
case "uniswap_v3":
|
||||
checks["pool_discovery"] = true
|
||||
checks["tick_calculation"] = true
|
||||
checks["concentrated_liquidity"] = true
|
||||
checks["fee_tier_support"] = true
|
||||
case "curve":
|
||||
checks["stable_swap_pricing"] = true
|
||||
checks["amplification_parameter"] = true
|
||||
checks["admin_fee_calculation"] = true
|
||||
case "balancer":
|
||||
checks["weighted_pool_pricing"] = true
|
||||
checks["stable_pool_pricing"] = true
|
||||
checks["swap_fee_calculation"] = true
|
||||
}
|
||||
|
||||
return checks
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) performExchangeSpecificChecks(ctx context.Context, exchange string, result *ExchangeAuditResult) {
|
||||
switch exchange {
|
||||
case "uniswap_v2":
|
||||
result.SpecificChecks["pair_validation"] = ea.checkUniswapV2Pairs(ctx)
|
||||
result.SpecificChecks["fee_consistency"] = ea.checkUniswapV2Fees(ctx)
|
||||
case "uniswap_v3":
|
||||
result.SpecificChecks["pool_validation"] = ea.checkUniswapV3Pools(ctx)
|
||||
result.SpecificChecks["tick_spacing"] = ea.checkUniswapV3TickSpacing(ctx)
|
||||
case "curve":
|
||||
result.SpecificChecks["pool_registry"] = ea.checkCurveRegistry(ctx)
|
||||
result.SpecificChecks["price_oracle"] = ea.checkCurveOracle(ctx)
|
||||
case "balancer":
|
||||
result.SpecificChecks["vault_integration"] = ea.checkBalancerVault(ctx)
|
||||
result.SpecificChecks["pool_tokens"] = ea.checkBalancerPoolTokens(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkUniswapV2Pairs(ctx context.Context) CheckResult {
|
||||
return CheckResult{
|
||||
Status: "VALIDATED",
|
||||
Passed: true,
|
||||
Score: 95.0,
|
||||
Details: "Uniswap V2 pair validation successful",
|
||||
Timestamp: time.Now(),
|
||||
Metadata: map[string]interface{}{"pairs_checked": 150},
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkUniswapV2Fees(ctx context.Context) CheckResult {
|
||||
return CheckResult{
|
||||
Status: "CONSISTENT",
|
||||
Passed: true,
|
||||
Score: 100.0,
|
||||
Details: "Fee calculation consistency verified",
|
||||
Timestamp: time.Now(),
|
||||
Metadata: map[string]interface{}{"fee_percentage": 0.3},
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkUniswapV3Pools(ctx context.Context) CheckResult {
|
||||
return CheckResult{
|
||||
Status: "VALIDATED",
|
||||
Passed: true,
|
||||
Score: 90.0,
|
||||
Details: "Uniswap V3 pool validation successful",
|
||||
Timestamp: time.Now(),
|
||||
Metadata: map[string]interface{}{"pools_checked": 75, "fee_tiers": []int{500, 3000, 10000}},
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkUniswapV3TickSpacing(ctx context.Context) CheckResult {
|
||||
return CheckResult{
|
||||
Status: "CORRECT",
|
||||
Passed: true,
|
||||
Score: 100.0,
|
||||
Details: "Tick spacing calculations verified",
|
||||
Timestamp: time.Now(),
|
||||
Metadata: map[string]interface{}{"tick_spacings": map[int]int{500: 10, 3000: 60, 10000: 200}},
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkCurveRegistry(ctx context.Context) CheckResult {
|
||||
return CheckResult{
|
||||
Status: "ACCESSIBLE",
|
||||
Passed: true,
|
||||
Score: 85.0,
|
||||
Details: "Curve registry accessible and functional",
|
||||
Timestamp: time.Now(),
|
||||
Metadata: map[string]interface{}{"pools_in_registry": 120},
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkCurveOracle(ctx context.Context) CheckResult {
|
||||
return CheckResult{
|
||||
Status: "FUNCTIONAL",
|
||||
Passed: true,
|
||||
Score: 90.0,
|
||||
Details: "Curve price oracle functioning correctly",
|
||||
Timestamp: time.Now(),
|
||||
Metadata: map[string]interface{}{"oracle_latency_ms": 200},
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkBalancerVault(ctx context.Context) CheckResult {
|
||||
return CheckResult{
|
||||
Status: "INTEGRATED",
|
||||
Passed: true,
|
||||
Score: 95.0,
|
||||
Details: "Balancer vault integration successful",
|
||||
Timestamp: time.Now(),
|
||||
Metadata: map[string]interface{}{"vault_version": "v2"},
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) checkBalancerPoolTokens(ctx context.Context) CheckResult {
|
||||
return CheckResult{
|
||||
Status: "VALIDATED",
|
||||
Passed: true,
|
||||
Score: 88.0,
|
||||
Details: "Balancer pool token validation successful",
|
||||
Timestamp: time.Now(),
|
||||
Metadata: map[string]interface{}{"pool_types": []string{"weighted", "stable", "meta_stable"}},
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) calculateOverallScore() {
|
||||
if len(ea.results.ExchangeResults) == 0 {
|
||||
ea.results.OverallScore = 0.0
|
||||
return
|
||||
}
|
||||
|
||||
totalScore := 0.0
|
||||
for _, result := range ea.results.ExchangeResults {
|
||||
totalScore += result.Score
|
||||
}
|
||||
|
||||
ea.results.OverallScore = totalScore / float64(len(ea.results.ExchangeResults))
|
||||
|
||||
// Calculate summary scores
|
||||
var connectivityTotal, contractTotal, apiTotal, integrationTotal float64
|
||||
var connectivityCount, contractCount, apiCount, integrationCount int
|
||||
|
||||
for _, result := range ea.results.ExchangeResults {
|
||||
if ea.config.CheckConnectivity {
|
||||
connectivityTotal += result.ConnectivityCheck.Score
|
||||
connectivityCount++
|
||||
}
|
||||
if ea.config.CheckContracts {
|
||||
contractTotal += result.ContractCheck.Score
|
||||
contractCount++
|
||||
}
|
||||
if ea.config.CheckAPIs {
|
||||
apiTotal += result.APICheck.Score
|
||||
apiCount++
|
||||
}
|
||||
if ea.config.CheckIntegration {
|
||||
integrationTotal += result.IntegrationCheck.Score
|
||||
integrationCount++
|
||||
}
|
||||
}
|
||||
|
||||
ea.results.AuditSummary = AuditSummary{
|
||||
ConnectivityScore: connectivityTotal / float64(connectivityCount),
|
||||
ContractScore: contractTotal / float64(contractCount),
|
||||
APIScore: apiTotal / float64(apiCount),
|
||||
IntegrationScore: integrationTotal / float64(integrationCount),
|
||||
TotalChecks: ea.results.PassedExchanges + ea.results.FailedExchanges,
|
||||
PassedChecks: ea.results.PassedExchanges,
|
||||
FailedChecks: ea.results.FailedExchanges,
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) generateRecommendations() {
|
||||
if ea.results.OverallScore < 80.0 {
|
||||
ea.results.RecommendedActions = append(ea.results.RecommendedActions,
|
||||
"Overall exchange integration score is below 80%. Review failed exchanges and address critical issues.")
|
||||
}
|
||||
|
||||
if len(ea.results.CriticalIssues) > 0 {
|
||||
ea.results.RecommendedActions = append(ea.results.RecommendedActions,
|
||||
fmt.Sprintf("Address %d critical issues identified during audit.", len(ea.results.CriticalIssues)))
|
||||
}
|
||||
|
||||
if ea.results.AuditSummary.ConnectivityScore < 85.0 {
|
||||
ea.results.RecommendedActions = append(ea.results.RecommendedActions,
|
||||
"Improve connectivity reliability for exchanges with low connectivity scores.")
|
||||
}
|
||||
|
||||
if ea.results.AuditSummary.APIScore < 70.0 {
|
||||
ea.results.RecommendedActions = append(ea.results.RecommendedActions,
|
||||
"Review and fix API endpoint issues. Consider implementing fallback mechanisms.")
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) generateExchangeRecommendations(exchange string, result *ExchangeAuditResult) {
|
||||
if result.Score < 80.0 {
|
||||
result.Recommendations = append(result.Recommendations,
|
||||
fmt.Sprintf("Exchange %s score is below 80%%. Review integration implementation.", exchange))
|
||||
}
|
||||
|
||||
if !result.ConnectivityCheck.Passed {
|
||||
result.Recommendations = append(result.Recommendations,
|
||||
"Fix connectivity issues. Check RPC endpoints and network configuration.")
|
||||
}
|
||||
|
||||
if !result.ContractCheck.Passed {
|
||||
result.Recommendations = append(result.Recommendations,
|
||||
"Validate contract addresses and ensure they are deployed on the target network.")
|
||||
}
|
||||
|
||||
if !result.APICheck.Passed {
|
||||
result.Recommendations = append(result.Recommendations,
|
||||
"Fix API endpoint issues. Implement retry mechanisms and error handling.")
|
||||
}
|
||||
|
||||
if !result.IntegrationCheck.Passed {
|
||||
result.Recommendations = append(result.Recommendations,
|
||||
"Complete missing integration components. Ensure all required functions are implemented.")
|
||||
}
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) GenerateReport() error {
|
||||
// Sort exchange results by score (descending)
|
||||
sort.Slice(ea.results.ExchangeResults, func(i, j int) bool {
|
||||
return ea.results.ExchangeResults[i].Score > ea.results.ExchangeResults[j].Score
|
||||
})
|
||||
|
||||
// Generate JSON report
|
||||
jsonReport, err := json.MarshalIndent(ea.results, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal results: %w", err)
|
||||
}
|
||||
|
||||
// Save JSON report
|
||||
timestamp := time.Now().Format("2006-01-02_15-04-05")
|
||||
jsonPath := filepath.Join(ea.config.OutputDir, fmt.Sprintf("exchange_audit_%s.json", timestamp))
|
||||
if err := os.WriteFile(jsonPath, jsonReport, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write JSON report: %w", err)
|
||||
}
|
||||
|
||||
// Generate summary report
|
||||
summaryPath := filepath.Join(ea.config.OutputDir, fmt.Sprintf("exchange_summary_%s.txt", timestamp))
|
||||
if err := ea.generateSummaryReport(summaryPath); err != nil {
|
||||
return fmt.Errorf("failed to generate summary report: %w", err)
|
||||
}
|
||||
|
||||
if ea.config.Verbose {
|
||||
fmt.Printf("Reports generated:\n")
|
||||
fmt.Printf(" JSON: %s\n", jsonPath)
|
||||
fmt.Printf(" Summary: %s\n", summaryPath)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ea *ExchangeAuditor) generateSummaryReport(filePath string) error {
|
||||
summary := fmt.Sprintf(`Exchange Integration Audit Report
|
||||
Generated: %s
|
||||
Network: %s
|
||||
Duration: %d ms
|
||||
|
||||
OVERALL SUMMARY
|
||||
===============
|
||||
Overall Score: %.1f%%
|
||||
Total Exchanges: %d
|
||||
Passed Exchanges: %d
|
||||
Failed Exchanges: %d
|
||||
Success Rate: %.1f%%
|
||||
|
||||
CATEGORY SCORES
|
||||
===============
|
||||
Connectivity: %.1f%%
|
||||
Contracts: %.1f%%
|
||||
APIs: %.1f%%
|
||||
Integration: %.1f%%
|
||||
|
||||
EXCHANGE RESULTS
|
||||
================
|
||||
`, ea.results.Timestamp.Format("2006-01-02 15:04:05"),
|
||||
ea.results.NetworkAudited,
|
||||
ea.results.DurationMs,
|
||||
ea.results.OverallScore,
|
||||
ea.results.TotalExchanges,
|
||||
ea.results.PassedExchanges,
|
||||
ea.results.FailedExchanges,
|
||||
float64(ea.results.PassedExchanges)/float64(ea.results.TotalExchanges)*100,
|
||||
ea.results.AuditSummary.ConnectivityScore,
|
||||
ea.results.AuditSummary.ContractScore,
|
||||
ea.results.AuditSummary.APIScore,
|
||||
ea.results.AuditSummary.IntegrationScore)
|
||||
|
||||
for i, result := range ea.results.ExchangeResults {
|
||||
summary += fmt.Sprintf("%d. %s - %.1f%% (%s)\n",
|
||||
i+1, result.Exchange, result.Score, result.OverallStatus)
|
||||
}
|
||||
|
||||
if len(ea.results.CriticalIssues) > 0 {
|
||||
summary += "\nCRITICAL ISSUES\n===============\n"
|
||||
for _, issue := range ea.results.CriticalIssues {
|
||||
summary += fmt.Sprintf("- %s: %s\n", issue.Exchange, issue.Issue)
|
||||
}
|
||||
}
|
||||
|
||||
if len(ea.results.RecommendedActions) > 0 {
|
||||
summary += "\nRECOMMENDED ACTIONS\n==================\n"
|
||||
for i, action := range ea.results.RecommendedActions {
|
||||
summary += fmt.Sprintf("%d. %s\n", i+1, action)
|
||||
}
|
||||
}
|
||||
|
||||
return os.WriteFile(filePath, []byte(summary), 0644)
|
||||
}
|
||||
65
orig/tools/exchange-audit/main.go
Normal file
65
orig/tools/exchange-audit/main.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/exchange-audit/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
exchanges = flag.String("exchanges", "uniswap_v2,uniswap_v3,curve,balancer", "Comma-separated list of exchanges to audit")
|
||||
network = flag.String("network", "arbitrum", "Network to audit (arbitrum, ethereum)")
|
||||
outputDir = flag.String("output", "reports/exchange-audit", "Output directory")
|
||||
verbose = flag.Bool("verbose", false, "Enable verbose output")
|
||||
deepCheck = flag.Bool("deep", false, "Perform deep integration checks")
|
||||
connectivity = flag.Bool("connectivity", true, "Check exchange connectivity")
|
||||
contracts = flag.Bool("contracts", true, "Validate contract addresses")
|
||||
apis = flag.Bool("apis", true, "Test API endpoints")
|
||||
integration = flag.Bool("integration", true, "Test integration completeness")
|
||||
timeout = flag.Duration("timeout", 5*time.Minute, "Timeout for audit operations")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
// Create output directory
|
||||
if err := os.MkdirAll(*outputDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Initialize exchange auditor
|
||||
auditor, err := internal.NewExchangeAuditor(&internal.ExchangeAuditConfig{
|
||||
Exchanges: *exchanges,
|
||||
Network: *network,
|
||||
OutputDir: *outputDir,
|
||||
Verbose: *verbose,
|
||||
DeepCheck: *deepCheck,
|
||||
CheckConnectivity: *connectivity,
|
||||
CheckContracts: *contracts,
|
||||
CheckAPIs: *apis,
|
||||
CheckIntegration: *integration,
|
||||
Timeout: *timeout,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize exchange auditor: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, *timeout)
|
||||
defer cancel()
|
||||
|
||||
fmt.Printf("Starting exchange integration audit for %s network...\n", *network)
|
||||
if err := auditor.AuditExchanges(ctx); err != nil {
|
||||
log.Fatalf("Exchange audit failed: %v", err)
|
||||
}
|
||||
|
||||
if err := auditor.GenerateReport(); err != nil {
|
||||
log.Fatalf("Report generation failed: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Exchange audit complete. Reports saved to: %s\n", *outputDir)
|
||||
}
|
||||
7
orig/tools/gas-audit/go.mod
Normal file
7
orig/tools/gas-audit/go.mod
Normal file
@@ -0,0 +1,7 @@
|
||||
module github.com/fraktal/mev-beta/tools/gas-audit
|
||||
|
||||
go 1.24
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../../
|
||||
|
||||
require github.com/fraktal/mev-beta v0.0.0-00010101000000-000000000000
|
||||
577
orig/tools/gas-audit/internal/gas_auditor.go
Normal file
577
orig/tools/gas-audit/internal/gas_auditor.go
Normal file
@@ -0,0 +1,577 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/pkg/math"
|
||||
)
|
||||
|
||||
// GasAuditConfig holds configuration for gas auditing
|
||||
type GasAuditConfig struct {
|
||||
Network string
|
||||
GasPrice string
|
||||
ScenariosFile string
|
||||
OutputDir string
|
||||
Verbose bool
|
||||
Tolerance float64 // Percentage tolerance for gas estimation accuracy
|
||||
}
|
||||
|
||||
// GasAuditor audits gas cost estimations and optimizations
|
||||
type GasAuditor struct {
|
||||
config *GasAuditConfig
|
||||
converter *math.DecimalConverter
|
||||
scenarios *GasScenarios
|
||||
results *GasAuditResults
|
||||
}
|
||||
|
||||
// GasScenarios defines test scenarios for gas estimation
|
||||
type GasScenarios struct {
|
||||
Version string `json:"version"`
|
||||
Network string `json:"network"`
|
||||
Scenarios map[string]*GasScenario `json:"scenarios"`
|
||||
}
|
||||
|
||||
// GasScenario represents a gas estimation test case
|
||||
type GasScenario struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Operation string `json:"operation"` // "swap", "arbitrage", "flashloan"
|
||||
Exchange string `json:"exchange"`
|
||||
TokenIn string `json:"token_in"`
|
||||
TokenOut string `json:"token_out"`
|
||||
AmountIn string `json:"amount_in"`
|
||||
ExpectedGasUsed int64 `json:"expected_gas_used"`
|
||||
MaxGasPrice string `json:"max_gas_price"`
|
||||
Priority string `json:"priority"` // "low", "medium", "high"
|
||||
Complexity string `json:"complexity"` // "simple", "medium", "complex"
|
||||
}
|
||||
|
||||
// GasAuditResults holds comprehensive gas audit results
|
||||
type GasAuditResults struct {
|
||||
Network string `json:"network"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
TotalScenarios int `json:"total_scenarios"`
|
||||
PassedScenarios int `json:"passed_scenarios"`
|
||||
FailedScenarios int `json:"failed_scenarios"`
|
||||
AverageGasUsed int64 `json:"average_gas_used"`
|
||||
AverageGasPrice string `json:"average_gas_price"`
|
||||
TotalGasCostETH string `json:"total_gas_cost_eth"`
|
||||
EstimationAccuracy float64 `json:"estimation_accuracy"`
|
||||
ScenarioResults []*GasScenarioResult `json:"scenario_results"`
|
||||
FailedCases []*GasEstimationFailure `json:"failed_cases"`
|
||||
Recommendations []string `json:"recommendations"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
}
|
||||
|
||||
// GasScenarioResult represents the result of a gas estimation test
|
||||
type GasScenarioResult struct {
|
||||
ScenarioName string `json:"scenario_name"`
|
||||
Passed bool `json:"passed"`
|
||||
EstimatedGas int64 `json:"estimated_gas"`
|
||||
ActualGas int64 `json:"actual_gas"`
|
||||
EstimationError float64 `json:"estimation_error_percent"`
|
||||
GasPriceGwei string `json:"gas_price_gwei"`
|
||||
GasCostETH string `json:"gas_cost_eth"`
|
||||
OptimizationSuggestions []string `json:"optimization_suggestions"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
}
|
||||
|
||||
// GasEstimationFailure represents a failed gas estimation
|
||||
type GasEstimationFailure struct {
|
||||
ScenarioName string `json:"scenario_name"`
|
||||
Reason string `json:"reason"`
|
||||
ExpectedGas int64 `json:"expected_gas"`
|
||||
EstimatedGas int64 `json:"estimated_gas"`
|
||||
ErrorPercent float64 `json:"error_percent"`
|
||||
Severity string `json:"severity"`
|
||||
Impact string `json:"impact"`
|
||||
}
|
||||
|
||||
// NewGasAuditor creates a new gas auditor
|
||||
func NewGasAuditor(config *GasAuditConfig) (*GasAuditor, error) {
|
||||
converter := math.NewDecimalConverter()
|
||||
|
||||
// Load gas scenarios
|
||||
scenarios, err := loadGasScenarios(config.ScenariosFile, config.Network)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load gas scenarios: %w", err)
|
||||
}
|
||||
|
||||
return &GasAuditor{
|
||||
config: config,
|
||||
converter: converter,
|
||||
scenarios: scenarios,
|
||||
results: &GasAuditResults{
|
||||
Network: config.Network,
|
||||
ScenarioResults: []*GasScenarioResult{},
|
||||
FailedCases: []*GasEstimationFailure{},
|
||||
Recommendations: []string{},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// AuditGasCosts performs comprehensive gas cost auditing
|
||||
func (ga *GasAuditor) AuditGasCosts(ctx context.Context) error {
|
||||
startTime := time.Now()
|
||||
ga.results.Timestamp = startTime
|
||||
|
||||
if ga.config.Verbose {
|
||||
fmt.Printf("Starting gas cost audit for %s network...\n", ga.config.Network)
|
||||
}
|
||||
|
||||
ga.results.TotalScenarios = len(ga.scenarios.Scenarios)
|
||||
var totalGasUsed int64
|
||||
var totalGasCostETH *math.UniversalDecimal
|
||||
|
||||
// Initialize total gas cost
|
||||
totalGasCostETH, _ = math.NewUniversalDecimal(big.NewInt(0), 18, "ETH")
|
||||
|
||||
for name, scenario := range ga.scenarios.Scenarios {
|
||||
result, err := ga.runGasScenario(ctx, name, scenario)
|
||||
if err != nil {
|
||||
if ga.config.Verbose {
|
||||
fmt.Printf(" Failed scenario %s: %v\n", name, err)
|
||||
}
|
||||
|
||||
failure := &GasEstimationFailure{
|
||||
ScenarioName: name,
|
||||
Reason: err.Error(),
|
||||
ExpectedGas: scenario.ExpectedGasUsed,
|
||||
Severity: "high",
|
||||
Impact: "Gas estimation unreliable",
|
||||
}
|
||||
ga.results.FailedCases = append(ga.results.FailedCases, failure)
|
||||
ga.results.FailedScenarios++
|
||||
continue
|
||||
}
|
||||
|
||||
ga.results.ScenarioResults = append(ga.results.ScenarioResults, result)
|
||||
|
||||
if result.Passed {
|
||||
ga.results.PassedScenarios++
|
||||
totalGasUsed += result.EstimatedGas
|
||||
|
||||
// Add to total gas cost
|
||||
scenarioGasCost, _ := ga.converter.FromString(result.GasCostETH, 18, "ETH")
|
||||
totalGasCostETH, _ = ga.converter.Add(totalGasCostETH, scenarioGasCost)
|
||||
} else {
|
||||
ga.results.FailedScenarios++
|
||||
|
||||
failure := &GasEstimationFailure{
|
||||
ScenarioName: name,
|
||||
Reason: result.ErrorMessage,
|
||||
ExpectedGas: scenario.ExpectedGasUsed,
|
||||
EstimatedGas: result.EstimatedGas,
|
||||
ErrorPercent: result.EstimationError,
|
||||
Severity: ga.calculateGasSeverity(result.EstimationError),
|
||||
Impact: ga.calculateGasImpact(result.EstimationError),
|
||||
}
|
||||
ga.results.FailedCases = append(ga.results.FailedCases, failure)
|
||||
}
|
||||
|
||||
if ga.config.Verbose {
|
||||
status := "✓"
|
||||
if !result.Passed {
|
||||
status = "✗"
|
||||
}
|
||||
fmt.Printf(" %s %s: Gas=%d, Cost=%s ETH, Error=%.1f%%\n",
|
||||
status, name, result.EstimatedGas, result.GasCostETH, result.EstimationError)
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate summary statistics
|
||||
if ga.results.PassedScenarios > 0 {
|
||||
ga.results.AverageGasUsed = totalGasUsed / int64(ga.results.PassedScenarios)
|
||||
ga.results.EstimationAccuracy = float64(ga.results.PassedScenarios) / float64(ga.results.TotalScenarios) * 100
|
||||
}
|
||||
|
||||
ga.results.TotalGasCostETH = ga.converter.ToHumanReadable(totalGasCostETH)
|
||||
ga.results.Duration = time.Since(startTime)
|
||||
|
||||
// Generate recommendations
|
||||
ga.generateRecommendations()
|
||||
|
||||
if ga.config.Verbose {
|
||||
fmt.Printf("Gas audit completed: %d/%d scenarios passed (%.1f%% accuracy)\n",
|
||||
ga.results.PassedScenarios, ga.results.TotalScenarios, ga.results.EstimationAccuracy)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// runGasScenario executes a single gas estimation scenario
|
||||
func (ga *GasAuditor) runGasScenario(ctx context.Context, name string, scenario *GasScenario) (*GasScenarioResult, error) {
|
||||
startTime := time.Now()
|
||||
|
||||
// Simulate gas estimation based on operation complexity
|
||||
estimatedGas, err := ga.estimateGasForScenario(scenario)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gas estimation failed: %w", err)
|
||||
}
|
||||
|
||||
// Get current gas price
|
||||
gasPrice, err := ga.getCurrentGasPrice()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get gas price: %w", err)
|
||||
}
|
||||
|
||||
// Calculate gas cost in ETH
|
||||
gasCostWei := new(big.Int).Mul(big.NewInt(estimatedGas), gasPrice)
|
||||
gasCostETH, err := math.NewUniversalDecimal(gasCostWei, 18, "ETH")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to calculate gas cost: %w", err)
|
||||
}
|
||||
|
||||
// Calculate estimation error
|
||||
estimationError := ga.calculateEstimationError(scenario.ExpectedGasUsed, estimatedGas)
|
||||
|
||||
// Determine if estimation is within tolerance
|
||||
passed := estimationError <= ga.config.Tolerance
|
||||
|
||||
// Generate optimization suggestions
|
||||
optimizations := ga.generateOptimizationSuggestions(scenario, estimatedGas)
|
||||
|
||||
result := &GasScenarioResult{
|
||||
ScenarioName: name,
|
||||
Passed: passed,
|
||||
EstimatedGas: estimatedGas,
|
||||
ActualGas: scenario.ExpectedGasUsed,
|
||||
EstimationError: estimationError,
|
||||
GasPriceGwei: ga.weiToGwei(gasPrice),
|
||||
GasCostETH: ga.converter.ToHumanReadable(gasCostETH),
|
||||
OptimizationSuggestions: optimizations,
|
||||
Duration: time.Since(startTime),
|
||||
}
|
||||
|
||||
if !passed {
|
||||
result.ErrorMessage = fmt.Sprintf("Gas estimation error %.1f%% exceeds tolerance %.1f%%",
|
||||
estimationError, ga.config.Tolerance)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// estimateGasForScenario estimates gas for a specific scenario
|
||||
func (ga *GasAuditor) estimateGasForScenario(scenario *GasScenario) (int64, error) {
|
||||
// Base gas costs for different operations
|
||||
baseGas := map[string]int64{
|
||||
"swap": 150000,
|
||||
"arbitrage": 300000,
|
||||
"flashloan": 500000,
|
||||
}
|
||||
|
||||
// Complexity multipliers
|
||||
complexityMultiplier := map[string]float64{
|
||||
"simple": 1.0,
|
||||
"medium": 1.3,
|
||||
"complex": 1.8,
|
||||
}
|
||||
|
||||
// Exchange-specific adjustments
|
||||
exchangeAdjustment := map[string]float64{
|
||||
"uniswap_v2": 1.0,
|
||||
"uniswap_v3": 1.2,
|
||||
"curve": 0.8,
|
||||
"balancer": 1.5,
|
||||
}
|
||||
|
||||
base, exists := baseGas[scenario.Operation]
|
||||
if !exists {
|
||||
return 0, fmt.Errorf("unknown operation: %s", scenario.Operation)
|
||||
}
|
||||
|
||||
complexityMult, exists := complexityMultiplier[scenario.Complexity]
|
||||
if !exists {
|
||||
complexityMult = 1.0
|
||||
}
|
||||
|
||||
exchangeMult, exists := exchangeAdjustment[scenario.Exchange]
|
||||
if !exists {
|
||||
exchangeMult = 1.0
|
||||
}
|
||||
|
||||
// Calculate estimated gas
|
||||
estimated := float64(base) * complexityMult * exchangeMult
|
||||
|
||||
// Add some random variation to simulate real-world conditions
|
||||
variation := 0.9 + (0.2 * 0.5) // ±10% variation
|
||||
estimated *= variation
|
||||
|
||||
return int64(estimated), nil
|
||||
}
|
||||
|
||||
// getCurrentGasPrice returns current gas price for the network
|
||||
func (ga *GasAuditor) getCurrentGasPrice() (*big.Int, error) {
|
||||
// Simulate gas price based on network
|
||||
var gasPriceGwei int64
|
||||
|
||||
switch ga.config.Network {
|
||||
case "arbitrum":
|
||||
gasPriceGwei = 1 // Arbitrum typically has very low gas prices
|
||||
case "ethereum":
|
||||
gasPriceGwei = 20 // Ethereum mainnet
|
||||
default:
|
||||
gasPriceGwei = 10 // Default
|
||||
}
|
||||
|
||||
// Convert gwei to wei
|
||||
gweiToWei := new(big.Int).Exp(big.NewInt(10), big.NewInt(9), nil)
|
||||
gasPrice := new(big.Int).Mul(big.NewInt(gasPriceGwei), gweiToWei)
|
||||
|
||||
return gasPrice, nil
|
||||
}
|
||||
|
||||
// calculateEstimationError calculates the percentage error in gas estimation
|
||||
func (ga *GasAuditor) calculateEstimationError(expected, estimated int64) float64 {
|
||||
if expected == 0 {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
diff := float64(estimated - expected)
|
||||
if diff < 0 {
|
||||
diff = -diff
|
||||
}
|
||||
|
||||
return (diff / float64(expected)) * 100.0
|
||||
}
|
||||
|
||||
// generateOptimizationSuggestions generates gas optimization suggestions
|
||||
func (ga *GasAuditor) generateOptimizationSuggestions(scenario *GasScenario, estimatedGas int64) []string {
|
||||
var suggestions []string
|
||||
|
||||
// High gas usage suggestions
|
||||
if estimatedGas > 400000 {
|
||||
suggestions = append(suggestions, "Consider breaking complex operations into smaller transactions")
|
||||
suggestions = append(suggestions, "Evaluate if flash loans are necessary for this operation")
|
||||
}
|
||||
|
||||
// Exchange-specific suggestions
|
||||
switch scenario.Exchange {
|
||||
case "uniswap_v3":
|
||||
suggestions = append(suggestions, "Consider using single-hop swaps when possible")
|
||||
case "balancer":
|
||||
suggestions = append(suggestions, "Batch multiple operations to amortize gas costs")
|
||||
case "curve":
|
||||
suggestions = append(suggestions, "Leverage Curve's low slippage for stable swaps")
|
||||
}
|
||||
|
||||
// Operation-specific suggestions
|
||||
switch scenario.Operation {
|
||||
case "arbitrage":
|
||||
suggestions = append(suggestions, "Use multicall to bundle swap operations")
|
||||
suggestions = append(suggestions, "Consider gas price optimization strategies")
|
||||
case "flashloan":
|
||||
suggestions = append(suggestions, "Minimize logic in flash loan callback")
|
||||
}
|
||||
|
||||
return suggestions
|
||||
}
|
||||
|
||||
// calculateGasSeverity determines severity of gas estimation error
|
||||
func (ga *GasAuditor) calculateGasSeverity(errorPercent float64) string {
|
||||
switch {
|
||||
case errorPercent > 50:
|
||||
return "critical"
|
||||
case errorPercent > 30:
|
||||
return "high"
|
||||
case errorPercent > 15:
|
||||
return "medium"
|
||||
default:
|
||||
return "low"
|
||||
}
|
||||
}
|
||||
|
||||
// calculateGasImpact determines impact of gas estimation error
|
||||
func (ga *GasAuditor) calculateGasImpact(errorPercent float64) string {
|
||||
switch {
|
||||
case errorPercent > 50:
|
||||
return "Severe profit impact, transactions may fail"
|
||||
case errorPercent > 30:
|
||||
return "Significant profit reduction"
|
||||
case errorPercent > 15:
|
||||
return "Moderate profit impact"
|
||||
default:
|
||||
return "Minimal impact on profitability"
|
||||
}
|
||||
}
|
||||
|
||||
// generateRecommendations generates overall audit recommendations
|
||||
func (ga *GasAuditor) generateRecommendations() {
|
||||
if ga.results.EstimationAccuracy < 80 {
|
||||
ga.results.Recommendations = append(ga.results.Recommendations,
|
||||
"Gas estimation accuracy is below 80%. Consider improving estimation algorithms.")
|
||||
}
|
||||
|
||||
if ga.results.AverageGasUsed > 300000 {
|
||||
ga.results.Recommendations = append(ga.results.Recommendations,
|
||||
"Average gas usage is high. Consider optimizing transaction complexity.")
|
||||
}
|
||||
|
||||
if ga.results.FailedScenarios > ga.results.TotalScenarios/4 {
|
||||
ga.results.Recommendations = append(ga.results.Recommendations,
|
||||
"High failure rate detected. Review gas estimation methodology.")
|
||||
}
|
||||
|
||||
if ga.config.Network == "ethereum" {
|
||||
ga.results.Recommendations = append(ga.results.Recommendations,
|
||||
"Consider implementing EIP-1559 gas price optimization for Ethereum mainnet.")
|
||||
}
|
||||
}
|
||||
|
||||
// MonitorRealTimeGas monitors real-time gas costs and variations
|
||||
func (ga *GasAuditor) MonitorRealTimeGas(ctx context.Context) error {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
fmt.Printf("Monitoring real-time gas costs for %s...\n", ga.config.Network)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
gasPrice, err := ga.getCurrentGasPrice()
|
||||
if err != nil {
|
||||
if ga.config.Verbose {
|
||||
fmt.Printf("Error getting gas price: %v\n", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if ga.config.Verbose {
|
||||
fmt.Printf("[%s] Current gas price: %s gwei\n",
|
||||
time.Now().Format("15:04:05"), ga.weiToGwei(gasPrice))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateReport generates comprehensive gas audit reports
|
||||
func (ga *GasAuditor) GenerateReport() error {
|
||||
// Generate JSON report
|
||||
jsonPath := filepath.Join(ga.config.OutputDir, "gas_audit.json")
|
||||
if err := ga.generateJSONReport(jsonPath); err != nil {
|
||||
return fmt.Errorf("failed to generate JSON report: %w", err)
|
||||
}
|
||||
|
||||
// Generate Markdown report
|
||||
markdownPath := filepath.Join(ga.config.OutputDir, "gas_audit.md")
|
||||
if err := ga.generateMarkdownReport(markdownPath); err != nil {
|
||||
return fmt.Errorf("failed to generate Markdown report: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// generateJSONReport generates JSON format report
|
||||
func (ga *GasAuditor) generateJSONReport(path string) error {
|
||||
data, err := json.MarshalIndent(ga.results, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(path, data, 0644)
|
||||
}
|
||||
|
||||
// generateMarkdownReport generates Markdown format report
|
||||
func (ga *GasAuditor) generateMarkdownReport(path string) error {
|
||||
content := fmt.Sprintf("# Gas Cost Audit Report\n\n")
|
||||
content += fmt.Sprintf("**Network:** %s\n", ga.results.Network)
|
||||
content += fmt.Sprintf("**Generated:** %s\n\n", ga.results.Timestamp.Format(time.RFC3339))
|
||||
|
||||
content += fmt.Sprintf("## Summary\n\n")
|
||||
content += fmt.Sprintf("- Total Scenarios: %d\n", ga.results.TotalScenarios)
|
||||
content += fmt.Sprintf("- Passed: %d\n", ga.results.PassedScenarios)
|
||||
content += fmt.Sprintf("- Failed: %d\n", ga.results.FailedScenarios)
|
||||
content += fmt.Sprintf("- Estimation Accuracy: %.1f%%\n", ga.results.EstimationAccuracy)
|
||||
content += fmt.Sprintf("- Average Gas Used: %d\n", ga.results.AverageGasUsed)
|
||||
content += fmt.Sprintf("- Total Gas Cost: %s ETH\n\n", ga.results.TotalGasCostETH)
|
||||
|
||||
if len(ga.results.Recommendations) > 0 {
|
||||
content += fmt.Sprintf("## Recommendations\n\n")
|
||||
for _, rec := range ga.results.Recommendations {
|
||||
content += fmt.Sprintf("- %s\n", rec)
|
||||
}
|
||||
content += "\n"
|
||||
}
|
||||
|
||||
return os.WriteFile(path, []byte(content), 0644)
|
||||
}
|
||||
|
||||
// weiToGwei converts wei to gwei for display
|
||||
func (ga *GasAuditor) weiToGwei(wei *big.Int) string {
|
||||
gwei := new(big.Int).Div(wei, big.NewInt(1000000000))
|
||||
return gwei.String()
|
||||
}
|
||||
|
||||
// loadGasScenarios loads gas estimation scenarios
|
||||
func loadGasScenarios(filename, network string) (*GasScenarios, error) {
|
||||
// Create default scenarios if none specified
|
||||
if filename == "default" {
|
||||
return createDefaultGasScenarios(network), nil
|
||||
}
|
||||
|
||||
// TODO: Load from actual file
|
||||
return createDefaultGasScenarios(network), nil
|
||||
}
|
||||
|
||||
// createDefaultGasScenarios creates default gas estimation scenarios
|
||||
func createDefaultGasScenarios(network string) *GasScenarios {
|
||||
scenarios := &GasScenarios{
|
||||
Version: "1.0.0",
|
||||
Network: network,
|
||||
Scenarios: make(map[string]*GasScenario),
|
||||
}
|
||||
|
||||
// Base scenarios
|
||||
scenarios.Scenarios["simple_swap"] = &GasScenario{
|
||||
Name: "simple_swap",
|
||||
Description: "Simple token swap",
|
||||
Operation: "swap",
|
||||
Exchange: "uniswap_v2",
|
||||
TokenIn: "ETH",
|
||||
TokenOut: "USDC",
|
||||
AmountIn: "1000000000000000000",
|
||||
ExpectedGasUsed: 150000,
|
||||
MaxGasPrice: "50000000000",
|
||||
Priority: "medium",
|
||||
Complexity: "simple",
|
||||
}
|
||||
|
||||
scenarios.Scenarios["complex_arbitrage"] = &GasScenario{
|
||||
Name: "complex_arbitrage",
|
||||
Description: "Multi-hop arbitrage",
|
||||
Operation: "arbitrage",
|
||||
Exchange: "uniswap_v3",
|
||||
TokenIn: "ETH",
|
||||
TokenOut: "USDC",
|
||||
AmountIn: "10000000000000000000",
|
||||
ExpectedGasUsed: 400000,
|
||||
MaxGasPrice: "100000000000",
|
||||
Priority: "high",
|
||||
Complexity: "complex",
|
||||
}
|
||||
|
||||
scenarios.Scenarios["flashloan_arbitrage"] = &GasScenario{
|
||||
Name: "flashloan_arbitrage",
|
||||
Description: "Flash loan arbitrage",
|
||||
Operation: "flashloan",
|
||||
Exchange: "balancer",
|
||||
TokenIn: "ETH",
|
||||
TokenOut: "USDC",
|
||||
AmountIn: "100000000000000000000",
|
||||
ExpectedGasUsed: 600000,
|
||||
MaxGasPrice: "150000000000",
|
||||
Priority: "high",
|
||||
Complexity: "complex",
|
||||
}
|
||||
|
||||
return scenarios
|
||||
}
|
||||
67
orig/tools/gas-audit/main.go
Normal file
67
orig/tools/gas-audit/main.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/gas-audit/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
network = flag.String("network", "arbitrum", "Network to audit (arbitrum, ethereum)")
|
||||
gasPrice = flag.String("gas-price", "auto", "Gas price in gwei (auto for dynamic)")
|
||||
scenarios = flag.String("scenarios", "default", "Gas estimation scenarios")
|
||||
outputDir = flag.String("output", "reports/gas", "Output directory")
|
||||
verbose = flag.Bool("verbose", false, "Enable verbose output")
|
||||
realtime = flag.Bool("realtime", false, "Monitor real-time gas costs")
|
||||
duration = flag.Duration("duration", 5*time.Minute, "Duration for real-time monitoring")
|
||||
tolerance = flag.Float64("tolerance", 15.0, "Gas estimation tolerance percentage")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
// Create output directory
|
||||
if err := os.MkdirAll(*outputDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Initialize gas auditor
|
||||
auditor, err := internal.NewGasAuditor(&internal.GasAuditConfig{
|
||||
Network: *network,
|
||||
GasPrice: *gasPrice,
|
||||
ScenariosFile: *scenarios,
|
||||
OutputDir: *outputDir,
|
||||
Verbose: *verbose,
|
||||
Tolerance: *tolerance,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize gas auditor: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
if *realtime {
|
||||
fmt.Printf("Starting real-time gas cost monitoring for %v...\n", *duration)
|
||||
ctx, cancel := context.WithTimeout(ctx, *duration)
|
||||
defer cancel()
|
||||
|
||||
if err := auditor.MonitorRealTimeGas(ctx); err != nil {
|
||||
log.Fatalf("Real-time gas monitoring failed: %v", err)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Running gas cost audit for %s network...\n", *network)
|
||||
if err := auditor.AuditGasCosts(ctx); err != nil {
|
||||
log.Fatalf("Gas audit failed: %v", err)
|
||||
}
|
||||
|
||||
if err := auditor.GenerateReport(); err != nil {
|
||||
log.Fatalf("Report generation failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("Gas audit complete. Reports saved to: %s\n", *outputDir)
|
||||
}
|
||||
82
orig/tools/main.go
Normal file
82
orig/tools/main.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/bridge"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// define subcommands
|
||||
applyCmd := flag.NewFlagSet("apply", flag.ExitOnError)
|
||||
revertCmd := flag.NewFlagSet("revert", flag.ExitOnError)
|
||||
runCmd := flag.NewFlagSet("run", flag.ExitOnError)
|
||||
summarizeCmd := flag.NewFlagSet("summarize", flag.ExitOnError)
|
||||
|
||||
// apply flags
|
||||
applyPatch := applyCmd.String("patch", "", "Path to patch file")
|
||||
applyBranch := applyCmd.String("branch", "", "Branch name to apply patch")
|
||||
|
||||
// revert flags
|
||||
revertBranchName := revertCmd.String("branch", "", "Branch name to revert")
|
||||
|
||||
// run flags
|
||||
runMode := runCmd.String("mode", "", "Execution mode (podman-compose)")
|
||||
|
||||
// summarize flags
|
||||
summarizeArtifacts := summarizeCmd.String("artifacts", "", "Path to artifacts directory")
|
||||
summarizeOut := summarizeCmd.String("out", "", "Output JSON file path")
|
||||
|
||||
// parse subcommand
|
||||
if len(os.Args) < 2 {
|
||||
log.Fatal("subcommand required: apply, revert, run, summarize")
|
||||
}
|
||||
|
||||
switch os.Args[1] {
|
||||
case "apply":
|
||||
applyCmd.Parse(os.Args[2:])
|
||||
if *applyPatch == "" || *applyBranch == "" {
|
||||
log.Fatal("--patch and --branch are required")
|
||||
}
|
||||
op := bridge.PatchOperation{
|
||||
PatchFile: *applyPatch,
|
||||
BranchName: *applyBranch,
|
||||
}
|
||||
if err := bridge.ApplyPatch(op); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
case "revert":
|
||||
revertCmd.Parse(os.Args[2:])
|
||||
if *revertBranchName == "" {
|
||||
log.Fatal("--branch is required")
|
||||
}
|
||||
if err := bridge.RevertBranch(*revertBranchName); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
case "run":
|
||||
runCmd.Parse(os.Args[2:])
|
||||
if *runMode == "podman-compose" {
|
||||
if err := bridge.RunPodmanCompose(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
log.Fatalf("unsupported run mode: %s", *runMode)
|
||||
}
|
||||
case "summarize":
|
||||
summarizeCmd.Parse(os.Args[2:])
|
||||
if *summarizeArtifacts == "" || *summarizeOut == "" {
|
||||
log.Fatal("--artifacts and --out are required")
|
||||
}
|
||||
cfg := bridge.SummarizeConfig{
|
||||
ArtifactsDir: *summarizeArtifacts,
|
||||
OutputFile: *summarizeOut,
|
||||
}
|
||||
if err := bridge.SummarizeArtifacts(cfg); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
default:
|
||||
log.Fatalf("unknown subcommand: %s", os.Args[1])
|
||||
}
|
||||
}
|
||||
256
orig/tools/math-audit/cmd/main.go
Normal file
256
orig/tools/math-audit/cmd/main.go
Normal file
@@ -0,0 +1,256 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
pkgmath "github.com/fraktal/mev-beta/pkg/math"
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal"
|
||||
)
|
||||
|
||||
var (
|
||||
vectorsFile string
|
||||
reportDir string
|
||||
verbose bool
|
||||
exchange string
|
||||
tolerance float64
|
||||
)
|
||||
|
||||
func main() {
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "math-audit",
|
||||
Short: "Math audit tool for MEV Bot exchange calculations",
|
||||
Long: `A comprehensive math audit tool that validates pricing calculations,
|
||||
amount in/out computations, and price impact calculations across all supported exchanges.`,
|
||||
}
|
||||
|
||||
var auditCmd = &cobra.Command{
|
||||
Use: "audit",
|
||||
Short: "Run comprehensive math audit",
|
||||
Long: "Validates pricing math across all supported exchanges using canonical test vectors",
|
||||
RunE: runAudit,
|
||||
}
|
||||
|
||||
var validateCmd = &cobra.Command{
|
||||
Use: "validate",
|
||||
Short: "Validate specific exchange calculations",
|
||||
Long: "Validates calculations for a specific exchange using provided test vectors",
|
||||
RunE: runValidate,
|
||||
}
|
||||
|
||||
var reportCmd = &cobra.Command{
|
||||
Use: "report",
|
||||
Short: "Generate audit reports",
|
||||
Long: "Generates JSON and Markdown audit reports from previous validation runs",
|
||||
RunE: runReport,
|
||||
}
|
||||
|
||||
// Global flags
|
||||
rootCmd.PersistentFlags().StringVar(&vectorsFile, "vectors", "default", "Test vectors file or preset (default, comprehensive)")
|
||||
rootCmd.PersistentFlags().StringVar(&reportDir, "report", "reports/math/latest", "Report output directory")
|
||||
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose output")
|
||||
|
||||
// Validate command flags
|
||||
validateCmd.Flags().StringVar(&exchange, "exchange", "", "Exchange to validate (uniswap_v2, uniswap_v3, curve, balancer, etc.)")
|
||||
validateCmd.Flags().Float64Var(&tolerance, "tolerance", 0.0001, "Error tolerance in basis points (0.0001 = 1bp)")
|
||||
|
||||
rootCmd.AddCommand(auditCmd, validateCmd, reportCmd)
|
||||
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func runAudit(cmd *cobra.Command, args []string) error {
|
||||
ctx := context.Background()
|
||||
|
||||
if verbose {
|
||||
fmt.Printf("Starting comprehensive math audit...\n")
|
||||
fmt.Printf("Vectors: %s\n", vectorsFile)
|
||||
fmt.Printf("Report Directory: %s\n", reportDir)
|
||||
}
|
||||
|
||||
// Load test vectors
|
||||
vectors, err := internal.LoadTestVectors(vectorsFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load test vectors: %w", err)
|
||||
}
|
||||
|
||||
// Initialize audit engine
|
||||
auditor := internal.NewMathAuditor(pkgmath.NewDecimalConverter(), tolerance)
|
||||
|
||||
// Run audit across all exchanges
|
||||
results := make(map[string]*internal.ExchangeAuditResult)
|
||||
exchanges := []string{"uniswap_v2", "uniswap_v3", "curve", "balancer", "algebra", "camelot"}
|
||||
|
||||
for _, exchangeType := range exchanges {
|
||||
if verbose {
|
||||
fmt.Printf("Auditing %s...\n", exchangeType)
|
||||
}
|
||||
|
||||
exchangeVectors := vectors.GetExchangeVectors(exchangeType)
|
||||
if exchangeVectors == nil {
|
||||
fmt.Printf("Warning: No vectors found for %s\n", exchangeType)
|
||||
continue
|
||||
}
|
||||
|
||||
result, err := auditor.AuditExchange(ctx, exchangeType, exchangeVectors)
|
||||
if err != nil {
|
||||
fmt.Printf("Error auditing %s: %v\n", exchangeType, err)
|
||||
continue
|
||||
}
|
||||
|
||||
results[exchangeType] = result
|
||||
|
||||
if verbose {
|
||||
fmt.Printf(" - Tests: %d, Passed: %d, Failed: %d, Max Error: %.4f bp\n",
|
||||
result.TotalTests, result.PassedTests, result.FailedTests, result.MaxErrorBP)
|
||||
}
|
||||
}
|
||||
|
||||
// Generate comprehensive report
|
||||
report := &internal.ComprehensiveAuditReport{
|
||||
Timestamp: time.Now(),
|
||||
VectorsFile: vectorsFile,
|
||||
ToleranceBP: tolerance * 10000, // Convert to basis points
|
||||
ExchangeResults: results,
|
||||
OverallPassed: true,
|
||||
TotalTests: 0,
|
||||
TotalPassed: 0,
|
||||
TotalFailed: 0,
|
||||
}
|
||||
|
||||
// Calculate overall statistics
|
||||
for _, result := range results {
|
||||
report.TotalTests += result.TotalTests
|
||||
report.TotalPassed += result.PassedTests
|
||||
report.TotalFailed += result.FailedTests
|
||||
if result.FailedTests > 0 {
|
||||
report.OverallPassed = false
|
||||
}
|
||||
}
|
||||
|
||||
// Save reports
|
||||
if err := saveReports(report, reportDir); err != nil {
|
||||
return fmt.Errorf("failed to save reports: %w", err)
|
||||
}
|
||||
|
||||
// Print summary
|
||||
fmt.Printf("\nMath Audit Complete:\n")
|
||||
fmt.Printf(" Total Tests: %d\n", report.TotalTests)
|
||||
fmt.Printf(" Passed: %d\n", report.TotalPassed)
|
||||
fmt.Printf(" Failed: %d\n", report.TotalFailed)
|
||||
fmt.Printf(" Overall Status: %s\n", map[bool]string{true: "PASS", false: "FAIL"}[report.OverallPassed])
|
||||
fmt.Printf(" Reports saved to: %s\n", reportDir)
|
||||
|
||||
if !report.OverallPassed {
|
||||
return fmt.Errorf("math audit failed - see report for details")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func runValidate(cmd *cobra.Command, args []string) error {
|
||||
if exchange == "" {
|
||||
return fmt.Errorf("exchange must be specified with --exchange flag")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
if verbose {
|
||||
fmt.Printf("Validating %s exchange calculations...\n", exchange)
|
||||
}
|
||||
|
||||
// Load test vectors
|
||||
vectors, err := internal.LoadTestVectors(vectorsFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load test vectors: %w", err)
|
||||
}
|
||||
|
||||
exchangeVectors := vectors.GetExchangeVectors(exchange)
|
||||
if exchangeVectors == nil {
|
||||
return fmt.Errorf("no test vectors found for exchange: %s", exchange)
|
||||
}
|
||||
|
||||
// Initialize auditor
|
||||
auditor := internal.NewMathAuditor(pkgmath.NewDecimalConverter(), tolerance)
|
||||
|
||||
// Run validation
|
||||
result, err := auditor.AuditExchange(ctx, exchange, exchangeVectors)
|
||||
if err != nil {
|
||||
return fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Print detailed results
|
||||
fmt.Printf("\nValidation Results for %s:\n", exchange)
|
||||
fmt.Printf(" Total Tests: %d\n", result.TotalTests)
|
||||
fmt.Printf(" Passed: %d\n", result.PassedTests)
|
||||
fmt.Printf(" Failed: %d\n", result.FailedTests)
|
||||
fmt.Printf(" Max Error: %.4f bp\n", result.MaxErrorBP)
|
||||
fmt.Printf(" Avg Error: %.4f bp\n", result.AvgErrorBP)
|
||||
|
||||
if len(result.FailedCases) > 0 {
|
||||
fmt.Printf("\nFailed Test Cases:\n")
|
||||
for i, failure := range result.FailedCases {
|
||||
if i >= 5 { // Limit output
|
||||
fmt.Printf(" ... and %d more\n", len(result.FailedCases)-5)
|
||||
break
|
||||
}
|
||||
fmt.Printf(" - %s: %.4f bp error\n", failure.TestName, failure.ErrorBP)
|
||||
}
|
||||
}
|
||||
|
||||
if result.FailedTests > 0 {
|
||||
return fmt.Errorf("validation failed for %s", exchange)
|
||||
}
|
||||
|
||||
fmt.Printf("\n✓ All tests passed for %s\n", exchange)
|
||||
return nil
|
||||
}
|
||||
|
||||
func runReport(cmd *cobra.Command, args []string) error {
|
||||
// Load existing audit results and generate fresh reports
|
||||
fmt.Printf("Generating audit reports in %s...\n", reportDir)
|
||||
|
||||
// This would load existing JSON data and regenerate markdown reports
|
||||
// For now, just indicate the feature exists
|
||||
fmt.Printf("Report generation feature coming soon.\n")
|
||||
fmt.Printf("Run 'math-audit audit' to generate fresh audit reports.\n")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveReports(report *internal.ComprehensiveAuditReport, reportDir string) error {
|
||||
// Ensure report directory exists
|
||||
if err := os.MkdirAll(reportDir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Save JSON report
|
||||
jsonFile := filepath.Join(reportDir, "audit_results.json")
|
||||
jsonData, err := json.MarshalIndent(report, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.WriteFile(jsonFile, jsonData, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Save Markdown report
|
||||
markdownFile := filepath.Join(reportDir, "audit_report.md")
|
||||
markdownContent := internal.GenerateMarkdownReport(report)
|
||||
|
||||
if err := os.WriteFile(markdownFile, []byte(markdownContent), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
58
orig/tools/math-audit/go.mod
Normal file
58
orig/tools/math-audit/go.mod
Normal file
@@ -0,0 +1,58 @@
|
||||
module github.com/fraktal/mev-beta/tools/math-audit
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/fraktal/mev-beta v0.0.0
|
||||
github.com/spf13/cobra v1.8.1
|
||||
github.com/spf13/viper v1.17.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/StackExchange/wmi v1.2.1 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.24.0 // indirect
|
||||
github.com/consensys/gnark-crypto v0.19.0 // indirect
|
||||
github.com/crate-crypto/go-eth-kzg v1.4.0 // indirect
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect
|
||||
github.com/deckarep/golang-set/v2 v2.6.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
|
||||
github.com/ethereum/c-kzg-4844/v2 v2.1.2 // indirect
|
||||
github.com/ethereum/go-ethereum v1.16.3 // indirect
|
||||
github.com/ethereum/go-verkle v0.2.2 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/holiman/uint256 v1.3.2 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/olekukonko/errors v1.1.0 // indirect
|
||||
github.com/olekukonko/ll v0.1.1 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.3.0 // indirect
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.10.0 // indirect
|
||||
github.com/spf13/cast v1.5.1 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/supranational/blst v0.3.15 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.9.0 // indirect
|
||||
golang.org/x/crypto v0.42.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
golang.org/x/time v0.10.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../..
|
||||
677
orig/tools/math-audit/go.sum
Normal file
677
orig/tools/math-audit/go.sum
Normal file
@@ -0,0 +1,677 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
|
||||
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
|
||||
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
|
||||
cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
|
||||
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
|
||||
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
|
||||
cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To=
|
||||
cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4=
|
||||
cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M=
|
||||
cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc=
|
||||
cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk=
|
||||
cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs=
|
||||
cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc=
|
||||
cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY=
|
||||
cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI=
|
||||
cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk=
|
||||
cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY=
|
||||
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
|
||||
cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE=
|
||||
cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc=
|
||||
cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg=
|
||||
cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc=
|
||||
cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ=
|
||||
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
|
||||
cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk=
|
||||
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
|
||||
cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw=
|
||||
cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA=
|
||||
cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU=
|
||||
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
|
||||
cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos=
|
||||
cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk=
|
||||
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
|
||||
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
|
||||
cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo=
|
||||
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/DataDog/zstd v1.5.5 h1:oWf5W7GtOLgp6bciQYDmhHHjdhYkALu6S/5Ni9ZgSvQ=
|
||||
github.com/DataDog/zstd v1.5.5/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA=
|
||||
github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8=
|
||||
github.com/VictoriaMetrics/fastcache v1.12.2 h1:N0y9ASrJ0F6h0QaC3o6uJb3NIZ9VKLjCM7NQbSmF7WI=
|
||||
github.com/VictoriaMetrics/fastcache v1.12.2/go.mod h1:AmC+Nzz1+3G2eCPapF6UcsnkThDcMsQicp4xDukwJYI=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bits-and-blooms/bitset v1.24.0 h1:H4x4TuulnokZKvHLfzVRTHJfFfnHEeSYJizujEZvmAM=
|
||||
github.com/bits-and-blooms/bitset v1.24.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
|
||||
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
|
||||
github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I=
|
||||
github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8=
|
||||
github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4=
|
||||
github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce/go.mod h1:9/y3cnZ5GKakj/H4y9r9GTjCvAFta7KLgSHPJJYc52M=
|
||||
github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE=
|
||||
github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs=
|
||||
github.com/cockroachdb/pebble v1.1.5 h1:5AAWCBWbat0uE0blr8qzufZP5tBjkRyy/jWe1QWLnvw=
|
||||
github.com/cockroachdb/pebble v1.1.5/go.mod h1:17wO9el1YEigxkP/YtV8NtCivQDgoCyBg5c4VR/eOWo=
|
||||
github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30=
|
||||
github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg=
|
||||
github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo=
|
||||
github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ=
|
||||
github.com/consensys/gnark-crypto v0.19.0 h1:zXCqeY2txSaMl6G5wFpZzMWJU9HPNh8qxPnYJ1BL9vA=
|
||||
github.com/consensys/gnark-crypto v0.19.0/go.mod h1:rT23F0XSZqE0mUA0+pRtnL56IbPxs6gp4CeRsBk4XS0=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/crate-crypto/go-eth-kzg v1.4.0 h1:WzDGjHk4gFg6YzV0rJOAsTK4z3Qkz5jd4RE3DAvPFkg=
|
||||
github.com/crate-crypto/go-eth-kzg v1.4.0/go.mod h1:J9/u5sWfznSObptgfa92Jq8rTswn6ahQWEuiLHOjCUI=
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a h1:W8mUrRp6NOVl3J+MYp5kPMoUZPp7aOYHtaua31lwRHg=
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a/go.mod h1:sTwzHBvIzm2RfVCGNEBZgRyjwK40bVoun3ZnGOCafNM=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dchest/siphash v1.2.3 h1:QXwFc8cFOR2dSa/gE6o/HokBMWtLUaNDVd+22aKHeEA=
|
||||
github.com/dchest/siphash v1.2.3/go.mod h1:0NvQU092bT0ipiFN++/rXm69QG9tVxLAlQHIXMPAkHc=
|
||||
github.com/deckarep/golang-set/v2 v2.6.0 h1:XfcQbWM1LlMB8BsJ8N9vW5ehnnPVIw0je80NsVHagjM=
|
||||
github.com/deckarep/golang-set/v2 v2.6.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
|
||||
github.com/emicklei/dot v1.6.2 h1:08GN+DD79cy/tzN6uLCT84+2Wk9u+wvqP+Hkx/dIR8A=
|
||||
github.com/emicklei/dot v1.6.2/go.mod h1:DeV7GvQtIw4h2u73RKBkkFdvVAz0D9fzeJrgPW6gy/s=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po=
|
||||
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/ethereum/c-kzg-4844/v2 v2.1.2 h1:TsHMflcX0Wjjdwvhtg39HOozknAlQKY9PnG5Zf3gdD4=
|
||||
github.com/ethereum/c-kzg-4844/v2 v2.1.2/go.mod h1:u59hRTTah4Co6i9fDWtiCjTrblJv0UwsqZKCc0GfgUs=
|
||||
github.com/ethereum/go-ethereum v1.16.3 h1:nDoBSrmsrPbrDIVLTkDQCy1U9KdHN+F2PzvMbDoS42Q=
|
||||
github.com/ethereum/go-ethereum v1.16.3/go.mod h1:Lrsc6bt9Gm9RyvhfFK53vboCia8kpF9nv+2Ukntnl+8=
|
||||
github.com/ethereum/go-verkle v0.2.2 h1:I2W0WjnrFUIzzVPwm8ykY+7pL2d4VhlsePn4j7cnFk8=
|
||||
github.com/ethereum/go-verkle v0.2.2/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/ferranbt/fastssz v0.1.4 h1:OCDB+dYDEQDvAgtAGnTSidK1Pe2tW3nFV40XyMkTeDY=
|
||||
github.com/ferranbt/fastssz v0.1.4/go.mod h1:Ea3+oeoRGGLGm5shYAeDgu6PGUlcvQhE2fILyD9+tGg=
|
||||
github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
|
||||
github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps=
|
||||
github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY=
|
||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E=
|
||||
github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
|
||||
github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
|
||||
github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
|
||||
github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
|
||||
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk=
|
||||
github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
|
||||
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
||||
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
||||
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
||||
github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
|
||||
github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
|
||||
github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
|
||||
github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
|
||||
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
|
||||
github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
|
||||
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
|
||||
github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/go-bexpr v0.1.11 h1:6DqdA/KBjurGby9yTY0bmkathya0lfwF2SeuubCI7dY=
|
||||
github.com/hashicorp/go-bexpr v0.1.11/go.mod h1:f03lAo0duBlDIUMGCuad8oLcgejw4m7U+N8T+6Kz1AE=
|
||||
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4 h1:X4egAf/gcS1zATw6wn4Ej8vjuVGxeHdan+bRb2ebyv4=
|
||||
github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4/go.mod h1:5GuXa7vkL8u9FkFuWdVvfR5ix8hRB7DbOAaYULamFpc=
|
||||
github.com/holiman/bloomfilter/v2 v2.0.3 h1:73e0e/V0tCydx14a0SCYS/EWCxgwLZ18CZcZKVu0fao=
|
||||
github.com/holiman/bloomfilter/v2 v2.0.3/go.mod h1:zpoh+gs7qcpqrHr3dB55AMiJwo0iURXE7ZOP9L9hSkA=
|
||||
github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA=
|
||||
github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E=
|
||||
github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc=
|
||||
github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7BdWus=
|
||||
github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
|
||||
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
|
||||
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
|
||||
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/leanovate/gopter v0.2.11 h1:vRjThO1EKPb/1NsDXuDrzldR28RLkBflWYcU9CvzWu4=
|
||||
github.com/leanovate/gopter v0.2.11/go.mod h1:aK3tzZP/C+p1m3SPRE4SYZFGP7jjkuSI4f7Xvpt0S9c=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
|
||||
github.com/minio/sha256-simd v1.0.0 h1:v1ta+49hkWZyvaKwrQB8elexRqm6Y0aMLjCNsrYxo6g=
|
||||
github.com/minio/sha256-simd v1.0.0/go.mod h1:OuYzVNI5vcoYIAmbIvHPl3N3jUzVedXbKy5RFepssQM=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/mitchellh/pointerstructure v1.2.0 h1:O+i9nHnXS3l/9Wu7r4NrEdwA2VFTicjUEN1uBnDo34A=
|
||||
github.com/mitchellh/pointerstructure v1.2.0/go.mod h1:BRAsLI5zgXmw97Lf6s25bs8ohIXc3tViBH44KcwB2g4=
|
||||
github.com/olekukonko/cat v0.0.0-20250808191157-46fba99501f3 h1:3o1yj5hu9LOTwjey1RE0IBaB4u1HCLbD+lDPhJrl8Y4=
|
||||
github.com/olekukonko/cat v0.0.0-20250808191157-46fba99501f3/go.mod h1:rEKTHC9roVVicUIfZK7DYrdIoM0EOr8mK1Hj5s3JjH0=
|
||||
github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
|
||||
github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
|
||||
github.com/olekukonko/ll v0.1.1 h1:9Dfeed5/Mgaxb9lHRAftLK9pVfYETvHn+If6lywVhJc=
|
||||
github.com/olekukonko/ll v0.1.1/go.mod h1:2dJo+hYZcJMLMbKwHEWvxCUbAOLc/CXWS9noET22Mdo=
|
||||
github.com/olekukonko/tablewriter v1.0.9 h1:XGwRsYLC2bY7bNd93Dk51bcPZksWZmLYuaTHR0FqfL8=
|
||||
github.com/olekukonko/tablewriter v1.0.9/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=
|
||||
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
|
||||
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
|
||||
github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8=
|
||||
github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s=
|
||||
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
|
||||
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
|
||||
github.com/pion/stun/v2 v2.0.0 h1:A5+wXKLAypxQri59+tmQKVs7+l6mMM+3d+eER9ifRU0=
|
||||
github.com/pion/stun/v2 v2.0.0/go.mod h1:22qRSh08fSEttYUmJZGlriq9+03jtVmXNODgLccj8GQ=
|
||||
github.com/pion/transport/v2 v2.2.1 h1:7qYnCBlpgSJNYMbLCKuSY9KbQdBFoETvPNETv0y4N7c=
|
||||
github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g=
|
||||
github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouANiM=
|
||||
github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4=
|
||||
github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w=
|
||||
github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM=
|
||||
github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc=
|
||||
github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
|
||||
github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
|
||||
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sagikazarmark/locafero v0.3.0 h1:zT7VEGWC2DTflmccN/5T1etyKvxSxpHsjb9cJvm4SvQ=
|
||||
github.com/sagikazarmark/locafero v0.3.0/go.mod h1:w+v7UsPNFwzF1cHuOajOOzoq4U7v/ig1mpRjqV+Bu1U=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible h1:Bn1aCHHRnjv4Bl16T8rcaFjYSrGrIZvpiGO6P3Q4GpU=
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.10.0 h1:EaGW2JJh15aKOejeuJ+wpFSHnbd7GE6Wvp3TsNhb6LY=
|
||||
github.com/spf13/afero v1.10.0/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ=
|
||||
github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA=
|
||||
github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48=
|
||||
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
|
||||
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.17.0 h1:I5txKw7MJasPL/BrfkbA0Jyo/oELqVmux4pR/UxOMfI=
|
||||
github.com/spf13/viper v1.17.0/go.mod h1:BmMMMLQXSbcHK6KAOiFLz0l5JHrU89OdIRHvsk0+yVI=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/supranational/blst v0.3.15 h1:rd9viN6tfARE5wv3KZJ9H8e1cg0jXW8syFCcsbHa76o=
|
||||
github.com/supranational/blst v0.3.15/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw=
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs=
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48=
|
||||
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
|
||||
github.com/urfave/cli/v2 v2.27.6 h1:VdRdS98FNhKZ8/Az8B7MTyGQmpIr36O1EHybx/LaZ4g=
|
||||
github.com/urfave/cli/v2 v2.27.6/go.mod h1:3Sevf16NykTbInEnD0yKkjDAeZDS0A6bzhBH5hrMvTQ=
|
||||
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
|
||||
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
|
||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
||||
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
||||
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk=
|
||||
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
|
||||
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
|
||||
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
|
||||
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
|
||||
golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
|
||||
golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
|
||||
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
|
||||
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
|
||||
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs=
|
||||
golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
|
||||
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
|
||||
golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
|
||||
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
|
||||
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
|
||||
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
|
||||
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
|
||||
golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
|
||||
golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
|
||||
golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
|
||||
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/time v0.13.0 h1:eUlYslOIt32DgYD6utsuUeHs4d7AsEYLuIAdg7FlYgI=
|
||||
golang.org/x/time v0.13.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
|
||||
golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
|
||||
golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
|
||||
golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
|
||||
golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
|
||||
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
|
||||
golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE=
|
||||
golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
|
||||
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
|
||||
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
|
||||
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
|
||||
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
|
||||
google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
|
||||
google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
|
||||
google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
|
||||
google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
|
||||
google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
|
||||
google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
|
||||
google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
|
||||
google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE=
|
||||
google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE=
|
||||
google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM=
|
||||
google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc=
|
||||
google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg=
|
||||
google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE=
|
||||
google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
|
||||
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
|
||||
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
|
||||
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
|
||||
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
|
||||
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
|
||||
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
|
||||
google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
|
||||
google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
|
||||
google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
|
||||
google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
|
||||
google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
|
||||
google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA=
|
||||
google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U=
|
||||
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||
google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA=
|
||||
google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
||||
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
|
||||
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||
google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||
google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60=
|
||||
google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
|
||||
google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||
google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
|
||||
google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8=
|
||||
google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4=
|
||||
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
|
||||
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
|
||||
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
|
||||
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
|
||||
349
orig/tools/math-audit/internal/audit/runner.go
Normal file
349
orig/tools/math-audit/internal/audit/runner.go
Normal file
@@ -0,0 +1,349 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mmath "github.com/fraktal/mev-beta/pkg/math"
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal/models"
|
||||
)
|
||||
|
||||
// TestResult captures the outcome of a single assertion.
|
||||
type TestResult struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Passed bool `json:"passed"`
|
||||
DeltaBPS float64 `json:"delta_bps"`
|
||||
Expected string `json:"expected"`
|
||||
Actual string `json:"actual"`
|
||||
Details string `json:"details,omitempty"`
|
||||
Annotations []string `json:"annotations,omitempty"`
|
||||
}
|
||||
|
||||
// VectorResult summarises the results for a single pool vector.
|
||||
type VectorResult struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Exchange string `json:"exchange"`
|
||||
Passed bool `json:"passed"`
|
||||
Tests []TestResult `json:"tests"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
}
|
||||
|
||||
// Summary aggregates overall audit statistics.
|
||||
type Summary struct {
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
TotalVectors int `json:"total_vectors"`
|
||||
VectorsPassed int `json:"vectors_passed"`
|
||||
TotalAssertions int `json:"total_assertions"`
|
||||
AssertionsPassed int `json:"assertions_passed"`
|
||||
PropertyChecks int `json:"property_checks"`
|
||||
PropertySucceeded int `json:"property_succeeded"`
|
||||
}
|
||||
|
||||
// Result is the top-level audit payload.
|
||||
type Result struct {
|
||||
Summary Summary `json:"summary"`
|
||||
Vectors []VectorResult `json:"vectors"`
|
||||
PropertyChecks []TestResult `json:"property_checks"`
|
||||
}
|
||||
|
||||
// Runner executes vector assertions using the math pricing engine.
|
||||
type Runner struct {
|
||||
dc *mmath.DecimalConverter
|
||||
engine *mmath.ExchangePricingEngine
|
||||
}
|
||||
|
||||
func NewRunner() *Runner {
|
||||
return &Runner{
|
||||
dc: mmath.NewDecimalConverter(),
|
||||
engine: mmath.NewExchangePricingEngine(),
|
||||
}
|
||||
}
|
||||
|
||||
// Run executes the provided vectors and property checks.
|
||||
func (r *Runner) Run(vectors []models.Vector, propertyChecks []TestResult) Result {
|
||||
var (
|
||||
vectorResults []VectorResult
|
||||
totalAssertions int
|
||||
assertionsPassed int
|
||||
vectorsPassed int
|
||||
)
|
||||
|
||||
for _, vec := range vectors {
|
||||
vr := r.evaluateVector(vec)
|
||||
vectorResults = append(vectorResults, vr)
|
||||
|
||||
allPassed := vr.Passed
|
||||
for _, tr := range vr.Tests {
|
||||
totalAssertions++
|
||||
if tr.Passed {
|
||||
assertionsPassed++
|
||||
} else {
|
||||
allPassed = false
|
||||
}
|
||||
}
|
||||
|
||||
if allPassed {
|
||||
vectorsPassed++
|
||||
}
|
||||
}
|
||||
|
||||
propPassed := 0
|
||||
for _, check := range propertyChecks {
|
||||
if check.Passed {
|
||||
propPassed++
|
||||
}
|
||||
}
|
||||
|
||||
summary := Summary{
|
||||
GeneratedAt: time.Now().UTC(),
|
||||
TotalVectors: len(vectorResults),
|
||||
VectorsPassed: vectorsPassed,
|
||||
TotalAssertions: totalAssertions,
|
||||
AssertionsPassed: assertionsPassed,
|
||||
PropertyChecks: len(propertyChecks),
|
||||
PropertySucceeded: propPassed,
|
||||
}
|
||||
|
||||
return Result{
|
||||
Summary: summary,
|
||||
Vectors: vectorResults,
|
||||
PropertyChecks: propertyChecks,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runner) evaluateVector(vec models.Vector) VectorResult {
|
||||
poolData, err := r.buildPool(vec.Pool)
|
||||
if err != nil {
|
||||
return VectorResult{
|
||||
Name: vec.Name,
|
||||
Description: vec.Description,
|
||||
Exchange: vec.Pool.Exchange,
|
||||
Passed: false,
|
||||
Errors: []string{fmt.Sprintf("build pool: %v", err)},
|
||||
}
|
||||
}
|
||||
|
||||
pricer, err := r.engine.GetExchangePricer(poolData.ExchangeType)
|
||||
if err != nil {
|
||||
return VectorResult{
|
||||
Name: vec.Name,
|
||||
Description: vec.Description,
|
||||
Exchange: vec.Pool.Exchange,
|
||||
Passed: false,
|
||||
Errors: []string{fmt.Sprintf("get pricer: %v", err)},
|
||||
}
|
||||
}
|
||||
|
||||
vr := VectorResult{
|
||||
Name: vec.Name,
|
||||
Description: vec.Description,
|
||||
Exchange: vec.Pool.Exchange,
|
||||
Passed: true,
|
||||
}
|
||||
|
||||
for _, test := range vec.Tests {
|
||||
tr := r.executeTest(test, pricer, poolData)
|
||||
vr.Tests = append(vr.Tests, tr)
|
||||
if !tr.Passed {
|
||||
vr.Passed = false
|
||||
}
|
||||
}
|
||||
|
||||
return vr
|
||||
}
|
||||
|
||||
func (r *Runner) executeTest(test models.TestCase, pricer mmath.ExchangePricer, pool *mmath.PoolData) TestResult {
|
||||
result := TestResult{Name: test.Name, Type: test.Type}
|
||||
|
||||
expected, err := r.toUniversalDecimal(test.Expected)
|
||||
if err != nil {
|
||||
result.Passed = false
|
||||
result.Details = fmt.Sprintf("parse expected: %v", err)
|
||||
return result
|
||||
}
|
||||
result.Expected = r.dc.ToHumanReadable(expected)
|
||||
|
||||
tolerance := test.ToleranceBPS
|
||||
if tolerance <= 0 {
|
||||
tolerance = 1 // default tolerance of 1 bp
|
||||
}
|
||||
|
||||
switch strings.ToLower(test.Type) {
|
||||
case "spot_price":
|
||||
actual, err := pricer.GetSpotPrice(pool)
|
||||
if err != nil {
|
||||
return failure(result, fmt.Sprintf("spot price: %v", err))
|
||||
}
|
||||
return r.compareDecimals(result, expected, actual, tolerance)
|
||||
|
||||
case "amount_out":
|
||||
if test.AmountIn == nil {
|
||||
return failure(result, "amount_in required for amount_out test")
|
||||
}
|
||||
amountIn, err := r.toUniversalDecimal(*test.AmountIn)
|
||||
if err != nil {
|
||||
return failure(result, fmt.Sprintf("parse amount_in: %v", err))
|
||||
}
|
||||
actual, err := pricer.CalculateAmountOut(amountIn, pool)
|
||||
if err != nil {
|
||||
return failure(result, fmt.Sprintf("calculate amount_out: %v", err))
|
||||
}
|
||||
return r.compareDecimals(result, expected, actual, tolerance)
|
||||
|
||||
case "amount_in":
|
||||
if test.AmountOut == nil {
|
||||
return failure(result, "amount_out required for amount_in test")
|
||||
}
|
||||
amountOut, err := r.toUniversalDecimal(*test.AmountOut)
|
||||
if err != nil {
|
||||
return failure(result, fmt.Sprintf("parse amount_out: %v", err))
|
||||
}
|
||||
actual, err := pricer.CalculateAmountIn(amountOut, pool)
|
||||
if err != nil {
|
||||
return failure(result, fmt.Sprintf("calculate amount_in: %v", err))
|
||||
}
|
||||
return r.compareDecimals(result, expected, actual, tolerance)
|
||||
|
||||
default:
|
||||
return failure(result, fmt.Sprintf("unsupported test type %q", test.Type))
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runner) compareDecimals(result TestResult, expected, actual *mmath.UniversalDecimal, tolerance float64) TestResult {
|
||||
convertedActual, err := r.dc.ConvertTo(actual, expected.Decimals, expected.Symbol)
|
||||
if err != nil {
|
||||
return failure(result, fmt.Sprintf("rescale actual: %v", err))
|
||||
}
|
||||
|
||||
diff := new(big.Int).Sub(convertedActual.Value, expected.Value)
|
||||
absDiff := new(big.Int).Abs(diff)
|
||||
|
||||
deltaBPS := math.Inf(1)
|
||||
if expected.Value.Sign() == 0 {
|
||||
if convertedActual.Value.Sign() == 0 {
|
||||
deltaBPS = 0
|
||||
}
|
||||
} else {
|
||||
// delta_bps = |actual - expected| / expected * 1e4
|
||||
numerator := new(big.Float).SetInt(absDiff)
|
||||
denominator := new(big.Float).SetInt(expected.Value)
|
||||
if denominator.Cmp(big.NewFloat(0)) != 0 {
|
||||
ratio := new(big.Float).Quo(numerator, denominator)
|
||||
bps := new(big.Float).Mul(ratio, big.NewFloat(10000))
|
||||
val, _ := bps.Float64()
|
||||
deltaBPS = val
|
||||
}
|
||||
}
|
||||
|
||||
result.DeltaBPS = deltaBPS
|
||||
result.Expected = r.dc.ToHumanReadable(expected)
|
||||
result.Actual = r.dc.ToHumanReadable(convertedActual)
|
||||
result.Passed = deltaBPS <= tolerance
|
||||
result.Annotations = append(result.Annotations, fmt.Sprintf("tolerance %.4f bps", tolerance))
|
||||
if !result.Passed {
|
||||
result.Details = fmt.Sprintf("delta %.4f bps exceeds tolerance %.4f", deltaBPS, tolerance)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func failure(result TestResult, msg string) TestResult {
|
||||
result.Passed = false
|
||||
result.Details = msg
|
||||
return result
|
||||
}
|
||||
|
||||
func (r *Runner) toUniversalDecimal(dec models.DecimalValue) (*mmath.UniversalDecimal, error) {
|
||||
if err := dec.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value, ok := new(big.Int).SetString(dec.Value, 10)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid integer %s", dec.Value)
|
||||
}
|
||||
return mmath.NewUniversalDecimal(value, dec.Decimals, dec.Symbol)
|
||||
}
|
||||
|
||||
func (r *Runner) buildPool(pool models.Pool) (*mmath.PoolData, error) {
|
||||
reserve0, err := r.toUniversalDecimal(pool.Reserve0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reserve0: %w", err)
|
||||
}
|
||||
reserve1, err := r.toUniversalDecimal(pool.Reserve1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reserve1: %w", err)
|
||||
}
|
||||
|
||||
pd := &mmath.PoolData{
|
||||
Address: pool.Address,
|
||||
ExchangeType: mmath.ExchangeType(pool.Exchange),
|
||||
Token0: mmath.TokenInfo{
|
||||
Address: pool.Token0.Address,
|
||||
Symbol: pool.Token0.Symbol,
|
||||
Decimals: pool.Token0.Decimals,
|
||||
},
|
||||
Token1: mmath.TokenInfo{
|
||||
Address: pool.Token1.Address,
|
||||
Symbol: pool.Token1.Symbol,
|
||||
Decimals: pool.Token1.Decimals,
|
||||
},
|
||||
Reserve0: reserve0,
|
||||
Reserve1: reserve1,
|
||||
}
|
||||
|
||||
if pool.Fee != nil {
|
||||
fee, err := r.toUniversalDecimal(*pool.Fee)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fee: %w", err)
|
||||
}
|
||||
pd.Fee = fee
|
||||
}
|
||||
|
||||
if pool.SqrtPriceX96 != "" {
|
||||
val, ok := new(big.Int).SetString(pool.SqrtPriceX96, 10)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("sqrt_price_x96 invalid")
|
||||
}
|
||||
pd.SqrtPriceX96 = val
|
||||
}
|
||||
|
||||
if pool.Tick != "" {
|
||||
val, ok := new(big.Int).SetString(pool.Tick, 10)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("tick invalid")
|
||||
}
|
||||
pd.Tick = val
|
||||
}
|
||||
|
||||
if pool.Liquidity != "" {
|
||||
val, ok := new(big.Int).SetString(pool.Liquidity, 10)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("liquidity invalid")
|
||||
}
|
||||
pd.Liquidity = val
|
||||
}
|
||||
|
||||
if pool.Amplification != "" {
|
||||
val, ok := new(big.Int).SetString(pool.Amplification, 10)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("amplification invalid")
|
||||
}
|
||||
pd.A = val
|
||||
}
|
||||
|
||||
if len(pool.Weights) > 0 {
|
||||
for _, w := range pool.Weights {
|
||||
ud, err := r.toUniversalDecimal(w)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("weight: %w", err)
|
||||
}
|
||||
pd.Weights = append(pd.Weights, ud)
|
||||
}
|
||||
}
|
||||
|
||||
return pd, nil
|
||||
}
|
||||
551
orig/tools/math-audit/internal/auditor.go
Normal file
551
orig/tools/math-audit/internal/auditor.go
Normal file
@@ -0,0 +1,551 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
"time"
|
||||
|
||||
pkgmath "github.com/fraktal/mev-beta/pkg/math"
|
||||
)
|
||||
|
||||
// MathAuditor performs comprehensive mathematical validation
|
||||
type MathAuditor struct {
|
||||
converter *pkgmath.DecimalConverter
|
||||
tolerance float64 // Error tolerance in decimal (0.0001 = 1bp)
|
||||
}
|
||||
|
||||
// NewMathAuditor creates a new math auditor
|
||||
func NewMathAuditor(converter *pkgmath.DecimalConverter, tolerance float64) *MathAuditor {
|
||||
return &MathAuditor{
|
||||
converter: converter,
|
||||
tolerance: tolerance,
|
||||
}
|
||||
}
|
||||
|
||||
// ExchangeAuditResult contains the results of auditing an exchange
|
||||
type ExchangeAuditResult struct {
|
||||
ExchangeType string `json:"exchange_type"`
|
||||
TotalTests int `json:"total_tests"`
|
||||
PassedTests int `json:"passed_tests"`
|
||||
FailedTests int `json:"failed_tests"`
|
||||
MaxErrorBP float64 `json:"max_error_bp"`
|
||||
AvgErrorBP float64 `json:"avg_error_bp"`
|
||||
FailedCases []*TestFailure `json:"failed_cases"`
|
||||
TestResults []*IndividualTestResult `json:"test_results"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
}
|
||||
|
||||
// TestFailure represents a failed test case
|
||||
type TestFailure struct {
|
||||
TestName string `json:"test_name"`
|
||||
ErrorBP float64 `json:"error_bp"`
|
||||
Expected string `json:"expected"`
|
||||
Actual string `json:"actual"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// IndividualTestResult represents the result of a single test
|
||||
type IndividualTestResult struct {
|
||||
TestName string `json:"test_name"`
|
||||
Passed bool `json:"passed"`
|
||||
ErrorBP float64 `json:"error_bp"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// ComprehensiveAuditReport contains results from all exchanges
|
||||
type ComprehensiveAuditReport struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
VectorsFile string `json:"vectors_file"`
|
||||
ToleranceBP float64 `json:"tolerance_bp"`
|
||||
ExchangeResults map[string]*ExchangeAuditResult `json:"exchange_results"`
|
||||
OverallPassed bool `json:"overall_passed"`
|
||||
TotalTests int `json:"total_tests"`
|
||||
TotalPassed int `json:"total_passed"`
|
||||
TotalFailed int `json:"total_failed"`
|
||||
}
|
||||
|
||||
// AuditExchange performs comprehensive audit of an exchange's math
|
||||
func (a *MathAuditor) AuditExchange(ctx context.Context, exchangeType string, vectors *ExchangeVectors) (*ExchangeAuditResult, error) {
|
||||
startTime := time.Now()
|
||||
|
||||
result := &ExchangeAuditResult{
|
||||
ExchangeType: exchangeType,
|
||||
FailedCases: []*TestFailure{},
|
||||
TestResults: []*IndividualTestResult{},
|
||||
}
|
||||
|
||||
// Test pricing functions
|
||||
if err := a.auditPricingFunctions(ctx, exchangeType, vectors, result); err != nil {
|
||||
return nil, fmt.Errorf("pricing audit failed: %w", err)
|
||||
}
|
||||
|
||||
// Test amount calculations
|
||||
if err := a.auditAmountCalculations(ctx, exchangeType, vectors, result); err != nil {
|
||||
return nil, fmt.Errorf("amount calculation audit failed: %w", err)
|
||||
}
|
||||
|
||||
// Test price impact calculations
|
||||
if err := a.auditPriceImpact(ctx, exchangeType, vectors, result); err != nil {
|
||||
return nil, fmt.Errorf("price impact audit failed: %w", err)
|
||||
}
|
||||
|
||||
// Calculate statistics
|
||||
totalError := 0.0
|
||||
for _, testResult := range result.TestResults {
|
||||
if testResult.Passed {
|
||||
result.PassedTests++
|
||||
} else {
|
||||
result.FailedTests++
|
||||
}
|
||||
totalError += testResult.ErrorBP
|
||||
if testResult.ErrorBP > result.MaxErrorBP {
|
||||
result.MaxErrorBP = testResult.ErrorBP
|
||||
}
|
||||
}
|
||||
|
||||
result.TotalTests = len(result.TestResults)
|
||||
if result.TotalTests > 0 {
|
||||
result.AvgErrorBP = totalError / float64(result.TotalTests)
|
||||
}
|
||||
result.Duration = time.Since(startTime)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// auditPricingFunctions tests price conversion functions
|
||||
func (a *MathAuditor) auditPricingFunctions(ctx context.Context, exchangeType string, vectors *ExchangeVectors, result *ExchangeAuditResult) error {
|
||||
for _, test := range vectors.PricingTests {
|
||||
testResult := a.runPricingTest(exchangeType, test)
|
||||
result.TestResults = append(result.TestResults, testResult)
|
||||
|
||||
if !testResult.Passed {
|
||||
failure := &TestFailure{
|
||||
TestName: testResult.TestName,
|
||||
ErrorBP: testResult.ErrorBP,
|
||||
Description: fmt.Sprintf("Pricing test failed for %s", exchangeType),
|
||||
}
|
||||
result.FailedCases = append(result.FailedCases, failure)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// auditAmountCalculations tests amount in/out calculations
|
||||
func (a *MathAuditor) auditAmountCalculations(ctx context.Context, exchangeType string, vectors *ExchangeVectors, result *ExchangeAuditResult) error {
|
||||
for _, test := range vectors.AmountTests {
|
||||
testResult := a.runAmountTest(exchangeType, test)
|
||||
result.TestResults = append(result.TestResults, testResult)
|
||||
|
||||
if !testResult.Passed {
|
||||
failure := &TestFailure{
|
||||
TestName: testResult.TestName,
|
||||
ErrorBP: testResult.ErrorBP,
|
||||
Expected: test.ExpectedAmountOut,
|
||||
Actual: "calculated_amount", // Would be filled with actual calculated value
|
||||
Description: fmt.Sprintf("Amount calculation test failed for %s", exchangeType),
|
||||
}
|
||||
result.FailedCases = append(result.FailedCases, failure)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// auditPriceImpact tests price impact calculations
|
||||
func (a *MathAuditor) auditPriceImpact(ctx context.Context, exchangeType string, vectors *ExchangeVectors, result *ExchangeAuditResult) error {
|
||||
for _, test := range vectors.PriceImpactTests {
|
||||
testResult := a.runPriceImpactTest(exchangeType, test)
|
||||
result.TestResults = append(result.TestResults, testResult)
|
||||
|
||||
if !testResult.Passed {
|
||||
failure := &TestFailure{
|
||||
TestName: testResult.TestName,
|
||||
ErrorBP: testResult.ErrorBP,
|
||||
Description: fmt.Sprintf("Price impact test failed for %s", exchangeType),
|
||||
}
|
||||
result.FailedCases = append(result.FailedCases, failure)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// runPricingTest executes a single pricing test
|
||||
func (a *MathAuditor) runPricingTest(exchangeType string, test *PricingTest) *IndividualTestResult {
|
||||
startTime := time.Now()
|
||||
|
||||
// Convert test inputs to UniversalDecimal with proper decimals
|
||||
// For ETH/USDC: ETH has 18 decimals, USDC has 6 decimals
|
||||
// For WBTC/ETH: WBTC has 8 decimals, ETH has 18 decimals
|
||||
reserve0Decimals := uint8(18) // Default to 18 decimals
|
||||
reserve1Decimals := uint8(18) // Default to 18 decimals
|
||||
|
||||
// Determine decimals based on test name patterns
|
||||
if test.TestName == "ETH_USDC_Standard_Pool" || test.TestName == "ETH_USDC_Basic" {
|
||||
reserve0Decimals = 18 // ETH
|
||||
reserve1Decimals = 6 // USDC
|
||||
} else if test.TestName == "WBTC_ETH_High_Value" || test.TestName == "WBTC_ETH_Basic" {
|
||||
reserve0Decimals = 8 // WBTC
|
||||
reserve1Decimals = 18 // ETH
|
||||
} else if test.TestName == "Small_Pool_Precision" {
|
||||
reserve0Decimals = 18 // ETH
|
||||
reserve1Decimals = 6 // USDC
|
||||
} else if test.TestName == "Weighted_80_20_Pool" {
|
||||
reserve0Decimals = 18 // ETH
|
||||
reserve1Decimals = 6 // USDC
|
||||
} else if test.TestName == "Stable_USDC_USDT" {
|
||||
reserve0Decimals = 6 // USDC
|
||||
reserve1Decimals = 6 // USDT
|
||||
}
|
||||
|
||||
reserve0, _ := a.converter.FromString(test.Reserve0, reserve0Decimals, "TOKEN0")
|
||||
reserve1, _ := a.converter.FromString(test.Reserve1, reserve1Decimals, "TOKEN1")
|
||||
|
||||
// Calculate price using exchange-specific formula
|
||||
var calculatedPrice *pkgmath.UniversalDecimal
|
||||
var err error
|
||||
|
||||
switch exchangeType {
|
||||
case "uniswap_v2":
|
||||
calculatedPrice, err = a.calculateUniswapV2Price(reserve0, reserve1)
|
||||
case "uniswap_v3":
|
||||
// Uniswap V3 uses sqrtPriceX96, not reserves
|
||||
calculatedPrice, err = a.calculateUniswapV3Price(test)
|
||||
case "curve":
|
||||
calculatedPrice, err = a.calculateCurvePrice(test)
|
||||
case "balancer":
|
||||
calculatedPrice, err = a.calculateBalancerPrice(test)
|
||||
default:
|
||||
err = fmt.Errorf("unknown exchange type: %s", exchangeType)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return &IndividualTestResult{
|
||||
TestName: test.TestName,
|
||||
Passed: false,
|
||||
ErrorBP: 10000, // Max error
|
||||
Duration: time.Since(startTime),
|
||||
Description: fmt.Sprintf("Calculation failed: %v", err),
|
||||
}
|
||||
}
|
||||
|
||||
// Compare with expected result
|
||||
expectedPrice, _ := a.converter.FromString(test.ExpectedPrice, 18, "PRICE")
|
||||
errorBP := a.calculateErrorBP(expectedPrice, calculatedPrice)
|
||||
passed := errorBP <= a.tolerance*10000 // Convert tolerance to basis points
|
||||
|
||||
// Debug logging for failed tests
|
||||
if !passed {
|
||||
fmt.Printf("DEBUG: Test %s failed:\n", test.TestName)
|
||||
fmt.Printf(" SqrtPriceX96: %s\n", test.SqrtPriceX96)
|
||||
fmt.Printf(" Tick: %d\n", test.Tick)
|
||||
fmt.Printf(" Reserve0: %s (decimals: %d)\n", test.Reserve0, reserve0Decimals)
|
||||
fmt.Printf(" Reserve1: %s (decimals: %d)\n", test.Reserve1, reserve1Decimals)
|
||||
fmt.Printf(" Expected: %s\n", test.ExpectedPrice)
|
||||
fmt.Printf(" Calculated: %s\n", calculatedPrice.Value.String())
|
||||
fmt.Printf(" Error: %.4f bp\n", errorBP)
|
||||
fmt.Printf(" Normalized Reserve0: %s\n", reserve0.Value.String())
|
||||
fmt.Printf(" Normalized Reserve1: %s\n", reserve1.Value.String())
|
||||
}
|
||||
|
||||
return &IndividualTestResult{
|
||||
TestName: test.TestName,
|
||||
Passed: passed,
|
||||
ErrorBP: errorBP,
|
||||
Duration: time.Since(startTime),
|
||||
Description: fmt.Sprintf("Price calculation test for %s", exchangeType),
|
||||
}
|
||||
}
|
||||
|
||||
// runAmountTest executes a single amount calculation test
|
||||
func (a *MathAuditor) runAmountTest(exchangeType string, test *AmountTest) *IndividualTestResult {
|
||||
startTime := time.Now()
|
||||
|
||||
// Implementation would calculate actual amounts based on exchange type
|
||||
// For now, return a placeholder result
|
||||
|
||||
return &IndividualTestResult{
|
||||
TestName: test.TestName,
|
||||
Passed: true, // Placeholder
|
||||
ErrorBP: 0.0,
|
||||
Duration: time.Since(startTime),
|
||||
Description: fmt.Sprintf("Amount calculation test for %s", exchangeType),
|
||||
}
|
||||
}
|
||||
|
||||
// runPriceImpactTest executes a single price impact test
|
||||
func (a *MathAuditor) runPriceImpactTest(exchangeType string, test *PriceImpactTest) *IndividualTestResult {
|
||||
startTime := time.Now()
|
||||
|
||||
// Implementation would calculate actual price impact based on exchange type
|
||||
// For now, return a placeholder result
|
||||
|
||||
return &IndividualTestResult{
|
||||
TestName: test.TestName,
|
||||
Passed: true, // Placeholder
|
||||
ErrorBP: 0.0,
|
||||
Duration: time.Since(startTime),
|
||||
Description: fmt.Sprintf("Price impact test for %s", exchangeType),
|
||||
}
|
||||
}
|
||||
|
||||
// calculateUniswapV2Price calculates price for Uniswap V2 style AMM
|
||||
func (a *MathAuditor) calculateUniswapV2Price(reserve0, reserve1 *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
// Price = reserve1 / reserve0, accounting for decimal differences
|
||||
if reserve0.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return nil, fmt.Errorf("reserve0 cannot be zero")
|
||||
}
|
||||
|
||||
// Normalize both reserves to 18 decimals for calculation
|
||||
normalizedReserve0 := new(big.Int).Set(reserve0.Value)
|
||||
normalizedReserve1 := new(big.Int).Set(reserve1.Value)
|
||||
|
||||
// Adjust reserve0 to 18 decimals if needed
|
||||
if reserve0.Decimals < 18 {
|
||||
decimalDiff := 18 - reserve0.Decimals
|
||||
scaleFactor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimalDiff)), nil)
|
||||
normalizedReserve0.Mul(normalizedReserve0, scaleFactor)
|
||||
} else if reserve0.Decimals > 18 {
|
||||
decimalDiff := reserve0.Decimals - 18
|
||||
scaleFactor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimalDiff)), nil)
|
||||
normalizedReserve0.Div(normalizedReserve0, scaleFactor)
|
||||
}
|
||||
|
||||
// Adjust reserve1 to 18 decimals if needed
|
||||
if reserve1.Decimals < 18 {
|
||||
decimalDiff := 18 - reserve1.Decimals
|
||||
scaleFactor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimalDiff)), nil)
|
||||
normalizedReserve1.Mul(normalizedReserve1, scaleFactor)
|
||||
} else if reserve1.Decimals > 18 {
|
||||
decimalDiff := reserve1.Decimals - 18
|
||||
scaleFactor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimalDiff)), nil)
|
||||
normalizedReserve1.Div(normalizedReserve1, scaleFactor)
|
||||
}
|
||||
|
||||
// Calculate price = reserve1 / reserve0 with 18 decimal precision
|
||||
// Multiply by 10^18 to maintain precision during division
|
||||
price := new(big.Int).Mul(normalizedReserve1, new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
price.Div(price, normalizedReserve0)
|
||||
|
||||
result, err := pkgmath.NewUniversalDecimal(price, 18, "PRICE")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// calculateUniswapV3Price calculates price for Uniswap V3
|
||||
func (a *MathAuditor) calculateUniswapV3Price(test *PricingTest) (*pkgmath.UniversalDecimal, error) {
|
||||
var priceInt *big.Int
|
||||
|
||||
if test.SqrtPriceX96 != "" {
|
||||
// Method 1: Calculate from sqrtPriceX96
|
||||
sqrtPriceX96 := new(big.Int)
|
||||
_, success := sqrtPriceX96.SetString(test.SqrtPriceX96, 10)
|
||||
if !success {
|
||||
return nil, fmt.Errorf("invalid sqrtPriceX96 format")
|
||||
}
|
||||
|
||||
// Convert sqrtPriceX96 to price: price = (sqrtPriceX96 / 2^96)^2
|
||||
// For ETH/USDC: need to account for decimal differences (18 vs 6)
|
||||
q96 := new(big.Int).Lsh(big.NewInt(1), 96) // 2^96
|
||||
|
||||
// Calculate raw price first
|
||||
sqrtPriceFloat := new(big.Float).SetInt(sqrtPriceX96)
|
||||
q96Float := new(big.Float).SetInt(q96)
|
||||
sqrtPriceFloat.Quo(sqrtPriceFloat, q96Float)
|
||||
|
||||
// Square to get the price (token1/token0)
|
||||
priceFloat := new(big.Float).Mul(sqrtPriceFloat, sqrtPriceFloat)
|
||||
|
||||
// Account for decimal differences
|
||||
// ETH/USDC price should account for USDC having 6 decimals vs ETH's 18
|
||||
if test.TestName == "ETH_USDC_V3_SqrtPrice" || test.TestName == "ETH_USDC_V3_Basic" {
|
||||
// Multiply by 10^12 to account for USDC having 6 decimals instead of 18
|
||||
decimalAdjustment := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(12), nil))
|
||||
priceFloat.Mul(priceFloat, decimalAdjustment)
|
||||
}
|
||||
|
||||
// Convert to integer with 18 decimal precision for output
|
||||
scaleFactor := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceFloat.Mul(priceFloat, scaleFactor)
|
||||
|
||||
// Convert to big.Int
|
||||
priceInt, _ = priceFloat.Int(nil)
|
||||
|
||||
} else if test.Tick != 0 {
|
||||
// Method 2: Calculate from tick
|
||||
// price = 1.0001^tick
|
||||
// For precision, we'll use: price = (1.0001^tick) * 10^18
|
||||
|
||||
// Convert tick to big.Float for calculation
|
||||
tick := big.NewFloat(float64(test.Tick))
|
||||
base := big.NewFloat(1.0001)
|
||||
|
||||
// Calculate 1.0001^tick using exp and log
|
||||
// price = exp(tick * ln(1.0001))
|
||||
tickFloat, _ := tick.Float64()
|
||||
baseFloat, _ := base.Float64()
|
||||
|
||||
priceFloat := math.Pow(baseFloat, tickFloat)
|
||||
|
||||
// Convert to big.Int with 18 decimal precision
|
||||
scaledPrice := priceFloat * 1e18
|
||||
priceInt = big.NewInt(int64(scaledPrice))
|
||||
|
||||
} else {
|
||||
return nil, fmt.Errorf("either sqrtPriceX96 or tick is required for Uniswap V3 price calculation")
|
||||
}
|
||||
|
||||
result, err := pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// calculateCurvePrice calculates price for Curve stable swaps
|
||||
func (a *MathAuditor) calculateCurvePrice(test *PricingTest) (*pkgmath.UniversalDecimal, error) {
|
||||
// For Curve stable swaps, price is typically close to 1:1 ratio
|
||||
// But we need to account for decimal differences and any imbalance
|
||||
|
||||
// Determine decimals based on test name
|
||||
reserve0Decimals := uint8(6) // USDC default
|
||||
reserve1Decimals := uint8(6) // USDT default
|
||||
|
||||
if test.TestName == "Stable_USDC_USDT" {
|
||||
reserve0Decimals = 6 // USDC
|
||||
reserve1Decimals = 6 // USDT
|
||||
}
|
||||
|
||||
reserve0, _ := a.converter.FromString(test.Reserve0, reserve0Decimals, "TOKEN0")
|
||||
reserve1, _ := a.converter.FromString(test.Reserve1, reserve1Decimals, "TOKEN1")
|
||||
|
||||
if reserve0.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return nil, fmt.Errorf("reserve0 cannot be zero")
|
||||
}
|
||||
|
||||
// For stable swaps, price = reserve1 / reserve0
|
||||
// But normalize both to 18 decimals first
|
||||
reserve0Normalized := new(big.Int).Set(reserve0.Value)
|
||||
reserve1Normalized := new(big.Int).Set(reserve1.Value)
|
||||
|
||||
// Scale to 18 decimals
|
||||
if reserve0Decimals < 18 {
|
||||
scale0 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve0Decimals)), nil)
|
||||
reserve0Normalized.Mul(reserve0Normalized, scale0)
|
||||
}
|
||||
if reserve1Decimals < 18 {
|
||||
scale1 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve1Decimals)), nil)
|
||||
reserve1Normalized.Mul(reserve1Normalized, scale1)
|
||||
}
|
||||
|
||||
// Calculate price = reserve1 / reserve0 in 18 decimal precision
|
||||
priceInt := new(big.Int).Mul(reserve1Normalized, new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceInt.Div(priceInt, reserve0Normalized)
|
||||
|
||||
return pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
}
|
||||
|
||||
// calculateBalancerPrice calculates price for Balancer weighted pools
|
||||
func (a *MathAuditor) calculateBalancerPrice(test *PricingTest) (*pkgmath.UniversalDecimal, error) {
|
||||
// For Balancer weighted pools, the price formula is:
|
||||
// price = (reserve1/weight1) / (reserve0/weight0) = (reserve1 * weight0) / (reserve0 * weight1)
|
||||
|
||||
// Determine decimals and weights based on test name
|
||||
reserve0Decimals := uint8(18) // ETH default
|
||||
reserve1Decimals := uint8(6) // USDC default
|
||||
weight0 := 80.0 // Default 80%
|
||||
weight1 := 20.0 // Default 20%
|
||||
|
||||
if test.TestName == "Weighted_80_20_Pool" {
|
||||
reserve0Decimals = 18 // ETH
|
||||
reserve1Decimals = 6 // USDC
|
||||
weight0 = 80.0 // 80% ETH
|
||||
weight1 = 20.0 // 20% USDC
|
||||
}
|
||||
|
||||
reserve0, _ := a.converter.FromString(test.Reserve0, reserve0Decimals, "TOKEN0")
|
||||
reserve1, _ := a.converter.FromString(test.Reserve1, reserve1Decimals, "TOKEN1")
|
||||
|
||||
if reserve0.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return nil, fmt.Errorf("reserve0 cannot be zero")
|
||||
}
|
||||
|
||||
// Normalize both reserves to 18 decimals
|
||||
reserve0Normalized := new(big.Int).Set(reserve0.Value)
|
||||
reserve1Normalized := new(big.Int).Set(reserve1.Value)
|
||||
|
||||
// Scale to 18 decimals
|
||||
if reserve0Decimals < 18 {
|
||||
scale0 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve0Decimals)), nil)
|
||||
reserve0Normalized.Mul(reserve0Normalized, scale0)
|
||||
}
|
||||
if reserve1Decimals < 18 {
|
||||
scale1 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve1Decimals)), nil)
|
||||
reserve1Normalized.Mul(reserve1Normalized, scale1)
|
||||
}
|
||||
|
||||
// Calculate weighted price: price = (reserve1 * weight0) / (reserve0 * weight1)
|
||||
// Use big.Float for weight calculations to maintain precision
|
||||
reserve1Float := new(big.Float).SetInt(reserve1Normalized)
|
||||
reserve0Float := new(big.Float).SetInt(reserve0Normalized)
|
||||
weight0Float := big.NewFloat(weight0)
|
||||
weight1Float := big.NewFloat(weight1)
|
||||
|
||||
// numerator = reserve1 * weight0
|
||||
numerator := new(big.Float).Mul(reserve1Float, weight0Float)
|
||||
// denominator = reserve0 * weight1
|
||||
denominator := new(big.Float).Mul(reserve0Float, weight1Float)
|
||||
|
||||
// price = numerator / denominator
|
||||
priceFloat := new(big.Float).Quo(numerator, denominator)
|
||||
|
||||
// Convert back to big.Int with 18 decimal precision
|
||||
scaleFactor := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceFloat.Mul(priceFloat, scaleFactor)
|
||||
|
||||
priceInt, _ := priceFloat.Int(nil)
|
||||
|
||||
return pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
}
|
||||
|
||||
// calculateErrorBP calculates error in basis points between expected and actual values
|
||||
func (a *MathAuditor) calculateErrorBP(expected, actual *pkgmath.UniversalDecimal) float64 {
|
||||
if expected.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
if actual.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return 0.0
|
||||
}
|
||||
return 10000.0 // Max error if expected is 0 but actual is not
|
||||
}
|
||||
|
||||
// Calculate relative error: |actual - expected| / expected
|
||||
diff := new(big.Int).Sub(actual.Value, expected.Value)
|
||||
if diff.Sign() < 0 {
|
||||
diff.Neg(diff)
|
||||
}
|
||||
|
||||
// Convert to float for percentage calculation
|
||||
expectedFloat, _ := new(big.Float).SetInt(expected.Value).Float64()
|
||||
diffFloat, _ := new(big.Float).SetInt(diff).Float64()
|
||||
|
||||
if expectedFloat == 0 {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
errorPercent := (diffFloat / expectedFloat) * 100
|
||||
errorBP := errorPercent * 100 // Convert to basis points
|
||||
|
||||
// Cap at 10000 BP (100%)
|
||||
if errorBP > 10000 {
|
||||
errorBP = 10000
|
||||
}
|
||||
|
||||
return errorBP
|
||||
}
|
||||
183
orig/tools/math-audit/internal/checks/checks.go
Normal file
183
orig/tools/math-audit/internal/checks/checks.go
Normal file
@@ -0,0 +1,183 @@
|
||||
package checks
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/rand"
|
||||
|
||||
"github.com/fraktal/mev-beta/pkg/uniswap"
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal/audit"
|
||||
)
|
||||
|
||||
// Run executes deterministic property/fuzz-style checks reused from the unit test suites.
|
||||
func Run() []audit.TestResult {
|
||||
return []audit.TestResult{
|
||||
runPriceConversionRoundTrip(),
|
||||
runTickConversionRoundTrip(),
|
||||
runPriceMonotonicity(),
|
||||
runPriceSymmetry(),
|
||||
}
|
||||
}
|
||||
|
||||
func newResult(name string) audit.TestResult {
|
||||
return audit.TestResult{
|
||||
Name: name,
|
||||
Type: "property",
|
||||
}
|
||||
}
|
||||
|
||||
func runPriceConversionRoundTrip() audit.TestResult {
|
||||
res := newResult("price_conversion_round_trip")
|
||||
rng := rand.New(rand.NewSource(1337))
|
||||
const tolerance = 0.001 // 0.1%
|
||||
failures := 0
|
||||
|
||||
for i := 0; i < 256; i++ {
|
||||
exponent := rng.Float64()*12 - 6
|
||||
price := math.Pow(10, exponent)
|
||||
if price <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
priceBig := new(big.Float).SetFloat64(price)
|
||||
sqrt := uniswap.PriceToSqrtPriceX96(priceBig)
|
||||
converted := uniswap.SqrtPriceX96ToPrice(sqrt)
|
||||
convertedFloat, _ := converted.Float64()
|
||||
|
||||
if price == 0 {
|
||||
continue
|
||||
}
|
||||
relErr := math.Abs(price-convertedFloat) / price
|
||||
if relErr > tolerance {
|
||||
failures++
|
||||
if failures >= 3 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if failures == 0 {
|
||||
res.Passed = true
|
||||
res.Details = "all samples within 0.1% tolerance"
|
||||
} else {
|
||||
res.Passed = false
|
||||
res.Details = fmt.Sprintf("%d samples exceeded tolerance", failures)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func runTickConversionRoundTrip() audit.TestResult {
|
||||
res := newResult("tick_conversion_round_trip")
|
||||
rng := rand.New(rand.NewSource(4242))
|
||||
failures := 0
|
||||
|
||||
for i := 0; i < 256; i++ {
|
||||
tick := rng.Intn(1774544) - 887272
|
||||
sqrt := uniswap.TickToSqrtPriceX96(tick)
|
||||
convertedTick := uniswap.SqrtPriceX96ToTick(sqrt)
|
||||
if diff := absInt(tick - convertedTick); diff > 1 {
|
||||
failures++
|
||||
if failures >= 3 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if failures == 0 {
|
||||
res.Passed = true
|
||||
res.Details = "ticks round-trip within ±1"
|
||||
} else {
|
||||
res.Passed = false
|
||||
res.Details = fmt.Sprintf("%d tick samples exceeded tolerance", failures)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func runPriceMonotonicity() audit.TestResult {
|
||||
res := newResult("price_monotonicity")
|
||||
rng := rand.New(rand.NewSource(9001))
|
||||
const tickStep = 500
|
||||
failures := 0
|
||||
|
||||
for i := 0; i < 128; i++ {
|
||||
base := rng.Intn(1774544) - 887272
|
||||
tick1 := base
|
||||
tick2 := base + tickStep
|
||||
if tick2 > 887272 {
|
||||
tick2 = 887272
|
||||
}
|
||||
|
||||
sqrt1 := uniswap.TickToSqrtPriceX96(tick1)
|
||||
sqrt2 := uniswap.TickToSqrtPriceX96(tick2)
|
||||
price1 := uniswap.SqrtPriceX96ToPrice(sqrt1)
|
||||
price2 := uniswap.SqrtPriceX96ToPrice(sqrt2)
|
||||
|
||||
p1, _ := price1.Float64()
|
||||
p2, _ := price2.Float64()
|
||||
if p2 <= p1 {
|
||||
failures++
|
||||
if failures >= 3 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if failures == 0 {
|
||||
res.Passed = true
|
||||
res.Details = "higher ticks produced higher prices"
|
||||
} else {
|
||||
res.Passed = false
|
||||
res.Details = fmt.Sprintf("%d monotonicity violations detected", failures)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func runPriceSymmetry() audit.TestResult {
|
||||
res := newResult("price_symmetry")
|
||||
rng := rand.New(rand.NewSource(2025))
|
||||
const tolerance = 0.001
|
||||
failures := 0
|
||||
|
||||
for i := 0; i < 128; i++ {
|
||||
price := math.Pow(10, rng.Float64()*6-3) // range around 0.001 - 1000
|
||||
if price <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
inverse := 1.0 / price
|
||||
priceBig := new(big.Float).SetFloat64(price)
|
||||
invBig := new(big.Float).SetFloat64(inverse)
|
||||
|
||||
sqrtPrice := uniswap.PriceToSqrtPriceX96(priceBig)
|
||||
sqrtInverse := uniswap.PriceToSqrtPriceX96(invBig)
|
||||
|
||||
convertedPrice := uniswap.SqrtPriceX96ToPrice(sqrtPrice)
|
||||
convertedInverse := uniswap.SqrtPriceX96ToPrice(sqrtInverse)
|
||||
|
||||
p, _ := convertedPrice.Float64()
|
||||
inv, _ := convertedInverse.Float64()
|
||||
if math.Abs(p*inv-1) > tolerance {
|
||||
failures++
|
||||
if failures >= 3 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if failures == 0 {
|
||||
res.Passed = true
|
||||
res.Details = "price * inverse remained within 0.1%"
|
||||
} else {
|
||||
res.Passed = false
|
||||
res.Details = fmt.Sprintf("%d symmetry samples exceeded tolerance", failures)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func absInt(v int) int {
|
||||
if v < 0 {
|
||||
return -v
|
||||
}
|
||||
return v
|
||||
}
|
||||
115
orig/tools/math-audit/internal/loader/loader.go
Normal file
115
orig/tools/math-audit/internal/loader/loader.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package loader
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal/models"
|
||||
)
|
||||
|
||||
const defaultVectorDir = "tools/math-audit/vectors"
|
||||
|
||||
// LoadVectors loads vectors based on the selector. The selector can be:
|
||||
// - "default" (load all embedded vectors)
|
||||
// - a comma-separated list of files or directories.
|
||||
func LoadVectors(selector string) ([]models.Vector, error) {
|
||||
if selector == "" || selector == "default" {
|
||||
return loadFromDir(defaultVectorDir)
|
||||
}
|
||||
|
||||
var all []models.Vector
|
||||
parts := strings.Split(selector, ",")
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
info, err := os.Stat(part)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stat %s: %w", part, err)
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
vecs, err := loadFromDir(part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, vecs...)
|
||||
continue
|
||||
}
|
||||
|
||||
vec, err := loadFromFile(part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, vec)
|
||||
}
|
||||
|
||||
return all, nil
|
||||
}
|
||||
|
||||
func loadFromDir(dir string) ([]models.Vector, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read dir %s: %w", dir, err)
|
||||
}
|
||||
|
||||
var vectors []models.Vector
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
if !strings.HasSuffix(entry.Name(), ".json") {
|
||||
continue
|
||||
}
|
||||
|
||||
path := filepath.Join(dir, entry.Name())
|
||||
vec, err := loadFromFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vectors = append(vectors, vec)
|
||||
}
|
||||
|
||||
return vectors, nil
|
||||
}
|
||||
|
||||
func loadFromFile(path string) (models.Vector, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return models.Vector{}, fmt.Errorf("read vector %s: %w", path, err)
|
||||
}
|
||||
|
||||
var vec models.Vector
|
||||
if err := json.Unmarshal(data, &vec); err != nil {
|
||||
return models.Vector{}, fmt.Errorf("decode vector %s: %w", path, err)
|
||||
}
|
||||
|
||||
if err := vec.Validate(); err != nil {
|
||||
return models.Vector{}, fmt.Errorf("validate vector %s: %w", path, err)
|
||||
}
|
||||
|
||||
return vec, nil
|
||||
}
|
||||
|
||||
// WalkVectors walks every vector JSON file in a directory hierarchy.
|
||||
func WalkVectors(root string, fn func(path string, vec models.Vector) error) error {
|
||||
return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() || !strings.HasSuffix(d.Name(), ".json") {
|
||||
return nil
|
||||
}
|
||||
vec, err := loadFromFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fn(path, vec)
|
||||
})
|
||||
}
|
||||
75
orig/tools/math-audit/internal/models/models.go
Normal file
75
orig/tools/math-audit/internal/models/models.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package models
|
||||
|
||||
import "fmt"
|
||||
|
||||
// DecimalValue represents a quantity with explicit decimals.
|
||||
type DecimalValue struct {
|
||||
Value string `json:"value"`
|
||||
Decimals uint8 `json:"decimals"`
|
||||
Symbol string `json:"symbol"`
|
||||
}
|
||||
|
||||
func (d DecimalValue) Validate() error {
|
||||
if d.Value == "" {
|
||||
return fmt.Errorf("decimal value missing raw value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Token describes basic token metadata used by the pricing engine.
|
||||
type Token struct {
|
||||
Address string `json:"address,omitempty"`
|
||||
Symbol string `json:"symbol"`
|
||||
Decimals uint8 `json:"decimals"`
|
||||
}
|
||||
|
||||
// Pool encapsulates the static parameters needed to price a pool.
|
||||
type Pool struct {
|
||||
Address string `json:"address"`
|
||||
Exchange string `json:"exchange"`
|
||||
Token0 Token `json:"token0"`
|
||||
Token1 Token `json:"token1"`
|
||||
Reserve0 DecimalValue `json:"reserve0"`
|
||||
Reserve1 DecimalValue `json:"reserve1"`
|
||||
Fee *DecimalValue `json:"fee,omitempty"`
|
||||
SqrtPriceX96 string `json:"sqrt_price_x96,omitempty"`
|
||||
Tick string `json:"tick,omitempty"`
|
||||
Liquidity string `json:"liquidity,omitempty"`
|
||||
Amplification string `json:"amplification,omitempty"`
|
||||
Weights []DecimalValue `json:"weights,omitempty"`
|
||||
}
|
||||
|
||||
// TestCase defines an assertion to run against a pool.
|
||||
type TestCase struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
InputToken string `json:"input_token,omitempty"`
|
||||
OutputToken string `json:"output_token,omitempty"`
|
||||
AmountIn *DecimalValue `json:"amount_in,omitempty"`
|
||||
AmountOut *DecimalValue `json:"amount_out,omitempty"`
|
||||
Expected DecimalValue `json:"expected"`
|
||||
ToleranceBPS float64 `json:"tolerance_bps"`
|
||||
}
|
||||
|
||||
// Vector bundles a pool with the checks that should hold true.
|
||||
type Vector struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Pool Pool `json:"pool"`
|
||||
Tests []TestCase `json:"tests"`
|
||||
}
|
||||
|
||||
func (v Vector) Validate() error {
|
||||
if v.Name == "" {
|
||||
return fmt.Errorf("vector missing name")
|
||||
}
|
||||
if v.Pool.Exchange == "" {
|
||||
return fmt.Errorf("vector %s missing exchange type", v.Name)
|
||||
}
|
||||
for _, t := range v.Tests {
|
||||
if t.Expected.Value == "" {
|
||||
return fmt.Errorf("vector %s test %s missing expected value", v.Name, t.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
408
orig/tools/math-audit/internal/property_tests.go
Normal file
408
orig/tools/math-audit/internal/property_tests.go
Normal file
@@ -0,0 +1,408 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
stdmath "math"
|
||||
"math/big"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
pkgmath "github.com/fraktal/mev-beta/pkg/math"
|
||||
)
|
||||
|
||||
// PropertyTestSuite implements mathematical property testing
|
||||
type PropertyTestSuite struct {
|
||||
auditor *MathAuditor
|
||||
converter *pkgmath.DecimalConverter
|
||||
rand *rand.Rand
|
||||
}
|
||||
|
||||
// NewPropertyTestSuite creates a new property test suite
|
||||
func NewPropertyTestSuite(auditor *MathAuditor) *PropertyTestSuite {
|
||||
return &PropertyTestSuite{
|
||||
auditor: auditor,
|
||||
converter: pkgmath.NewDecimalConverter(),
|
||||
rand: rand.New(rand.NewSource(42)), // Deterministic seed
|
||||
}
|
||||
}
|
||||
|
||||
// PropertyTestResult represents the result of a property test
|
||||
type PropertyTestResult struct {
|
||||
PropertyName string `json:"property_name"`
|
||||
TestCount int `json:"test_count"`
|
||||
PassCount int `json:"pass_count"`
|
||||
FailCount int `json:"fail_count"`
|
||||
MaxError float64 `json:"max_error_bp"`
|
||||
AvgError float64 `json:"avg_error_bp"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
Failures []*PropertyFailure `json:"failures,omitempty"`
|
||||
}
|
||||
|
||||
// PropertyFailure represents a property test failure
|
||||
type PropertyFailure struct {
|
||||
Input string `json:"input"`
|
||||
Expected string `json:"expected"`
|
||||
Actual string `json:"actual"`
|
||||
ErrorBP float64 `json:"error_bp"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// RunAllPropertyTests runs all mathematical property tests
|
||||
func (pts *PropertyTestSuite) RunAllPropertyTests(ctx context.Context) ([]*PropertyTestResult, error) {
|
||||
var results []*PropertyTestResult
|
||||
|
||||
// Test monotonicity properties
|
||||
if result, err := pts.TestPriceMonotonicity(ctx, 1000); err == nil {
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
// Test round-trip properties
|
||||
if result, err := pts.TestRoundTripProperties(ctx, 1000); err == nil {
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
// Test symmetry properties
|
||||
if result, err := pts.TestSymmetryProperties(ctx, 1000); err == nil {
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
// Test boundary properties
|
||||
if result, err := pts.TestBoundaryProperties(ctx, 500); err == nil {
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
// Test arithmetic properties
|
||||
if result, err := pts.TestArithmeticProperties(ctx, 1000); err == nil {
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// TestPriceMonotonicity tests that price functions are monotonic
|
||||
func (pts *PropertyTestSuite) TestPriceMonotonicity(ctx context.Context, testCount int) (*PropertyTestResult, error) {
|
||||
startTime := time.Now()
|
||||
result := &PropertyTestResult{
|
||||
PropertyName: "Price Monotonicity",
|
||||
TestCount: testCount,
|
||||
}
|
||||
|
||||
var totalError float64
|
||||
|
||||
for i := 0; i < testCount; i++ {
|
||||
// Generate two reserve ratios where ratio1 > ratio2
|
||||
reserve0_1 := pts.generateRandomReserve()
|
||||
reserve1_1 := pts.generateRandomReserve()
|
||||
|
||||
reserve0_2 := reserve0_1
|
||||
reserve1_2 := new(big.Int).Mul(reserve1_1, big.NewInt(2)) // Double reserve1 to decrease price
|
||||
|
||||
// Calculate prices
|
||||
price1, _ := pts.auditor.calculateUniswapV2Price(
|
||||
&pkgmath.UniversalDecimal{Value: reserve0_1, Decimals: 18, Symbol: "TOKEN0"},
|
||||
&pkgmath.UniversalDecimal{Value: reserve1_1, Decimals: 18, Symbol: "TOKEN1"},
|
||||
)
|
||||
|
||||
price2, _ := pts.auditor.calculateUniswapV2Price(
|
||||
&pkgmath.UniversalDecimal{Value: reserve0_2, Decimals: 18, Symbol: "TOKEN0"},
|
||||
&pkgmath.UniversalDecimal{Value: reserve1_2, Decimals: 18, Symbol: "TOKEN1"},
|
||||
)
|
||||
|
||||
if price1 == nil || price2 == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Price2 should be greater than Price1 (more reserve1 means higher price per token0)
|
||||
if price2.Value.Cmp(price1.Value) <= 0 {
|
||||
failure := &PropertyFailure{
|
||||
Input: fmt.Sprintf("Reserve0: %s, Reserve1_1: %s, Reserve1_2: %s", reserve0_1.String(), reserve1_1.String(), reserve1_2.String()),
|
||||
Expected: fmt.Sprintf("Price2 > Price1 (%s)", price1.Value.String()),
|
||||
Actual: fmt.Sprintf("Price2 = %s", price2.Value.String()),
|
||||
ErrorBP: 100.0, // Categorical error
|
||||
Description: "Monotonicity violation: increasing reserve should increase price",
|
||||
}
|
||||
result.Failures = append(result.Failures, failure)
|
||||
result.FailCount++
|
||||
totalError += 100.0
|
||||
} else {
|
||||
result.PassCount++
|
||||
}
|
||||
}
|
||||
|
||||
if result.TestCount > 0 {
|
||||
result.AvgError = totalError / float64(result.TestCount)
|
||||
}
|
||||
result.Duration = time.Since(startTime)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// TestRoundTripProperties tests that conversions are reversible
|
||||
func (pts *PropertyTestSuite) TestRoundTripProperties(ctx context.Context, testCount int) (*PropertyTestResult, error) {
|
||||
startTime := time.Now()
|
||||
result := &PropertyTestResult{
|
||||
PropertyName: "Round Trip Properties",
|
||||
TestCount: testCount,
|
||||
}
|
||||
|
||||
var totalError float64
|
||||
|
||||
for i := 0; i < testCount; i++ {
|
||||
// Generate random price
|
||||
originalPrice := pts.generateRandomPrice()
|
||||
|
||||
// Convert to UniversalDecimal and back
|
||||
priceDecimal, err := pts.converter.FromString(fmt.Sprintf("%.18f", originalPrice), 18, "PRICE")
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Convert back to float - use a simple division approach
|
||||
recoveredPrice := 0.0
|
||||
if priceDecimal.Value.Cmp(big.NewInt(0)) > 0 {
|
||||
priceFloat := new(big.Float).SetInt(priceDecimal.Value)
|
||||
scaleFactor := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(priceDecimal.Decimals)), nil))
|
||||
priceFloat.Quo(priceFloat, scaleFactor)
|
||||
recoveredPrice, _ = priceFloat.Float64()
|
||||
}
|
||||
|
||||
// Calculate error
|
||||
errorBP := stdmath.Abs(recoveredPrice-originalPrice) / originalPrice * 10000
|
||||
totalError += errorBP
|
||||
|
||||
if errorBP > pts.auditor.tolerance*10000 {
|
||||
failure := &PropertyFailure{
|
||||
Input: fmt.Sprintf("%.18f", originalPrice),
|
||||
Expected: fmt.Sprintf("%.18f", originalPrice),
|
||||
Actual: fmt.Sprintf("%.18f", recoveredPrice),
|
||||
ErrorBP: errorBP,
|
||||
Description: "Round-trip conversion error exceeds tolerance",
|
||||
}
|
||||
result.Failures = append(result.Failures, failure)
|
||||
result.FailCount++
|
||||
} else {
|
||||
result.PassCount++
|
||||
}
|
||||
|
||||
if errorBP > result.MaxError {
|
||||
result.MaxError = errorBP
|
||||
}
|
||||
}
|
||||
|
||||
if result.TestCount > 0 {
|
||||
result.AvgError = totalError / float64(result.TestCount)
|
||||
}
|
||||
result.Duration = time.Since(startTime)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// TestSymmetryProperties tests mathematical symmetries
|
||||
func (pts *PropertyTestSuite) TestSymmetryProperties(ctx context.Context, testCount int) (*PropertyTestResult, error) {
|
||||
startTime := time.Now()
|
||||
result := &PropertyTestResult{
|
||||
PropertyName: "Symmetry Properties",
|
||||
TestCount: testCount,
|
||||
}
|
||||
|
||||
var totalError float64
|
||||
|
||||
for i := 0; i < testCount; i++ {
|
||||
// Test that swapping tokens gives reciprocal price
|
||||
reserve0 := pts.generateRandomReserve()
|
||||
reserve1 := pts.generateRandomReserve()
|
||||
|
||||
// Calculate price TOKEN1/TOKEN0
|
||||
price1, _ := pts.auditor.calculateUniswapV2Price(
|
||||
&pkgmath.UniversalDecimal{Value: reserve0, Decimals: 18, Symbol: "TOKEN0"},
|
||||
&pkgmath.UniversalDecimal{Value: reserve1, Decimals: 18, Symbol: "TOKEN1"},
|
||||
)
|
||||
|
||||
// Calculate price TOKEN0/TOKEN1 (swapped)
|
||||
price2, _ := pts.auditor.calculateUniswapV2Price(
|
||||
&pkgmath.UniversalDecimal{Value: reserve1, Decimals: 18, Symbol: "TOKEN1"},
|
||||
&pkgmath.UniversalDecimal{Value: reserve0, Decimals: 18, Symbol: "TOKEN0"},
|
||||
)
|
||||
|
||||
if price1 == nil || price2 == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// price1 * price2 should equal 1 (within tolerance)
|
||||
product := new(big.Int).Mul(price1.Value, price2.Value)
|
||||
// Scale product to compare with 10^36 (18 + 18 decimals)
|
||||
expected := new(big.Int).Exp(big.NewInt(10), big.NewInt(36), nil)
|
||||
|
||||
// Calculate relative error
|
||||
diff := new(big.Int).Sub(product, expected)
|
||||
if diff.Sign() < 0 {
|
||||
diff.Neg(diff)
|
||||
}
|
||||
|
||||
expectedFloat, _ := new(big.Float).SetInt(expected).Float64()
|
||||
diffFloat, _ := new(big.Float).SetInt(diff).Float64()
|
||||
|
||||
errorBP := 0.0
|
||||
if expectedFloat > 0 {
|
||||
errorBP = (diffFloat / expectedFloat) * 10000
|
||||
}
|
||||
|
||||
totalError += errorBP
|
||||
|
||||
if errorBP > pts.auditor.tolerance*10000 {
|
||||
failure := &PropertyFailure{
|
||||
Input: fmt.Sprintf("Reserve0: %s, Reserve1: %s", reserve0.String(), reserve1.String()),
|
||||
Expected: "price1 * price2 = 1",
|
||||
Actual: fmt.Sprintf("price1 * price2 = %s", product.String()),
|
||||
ErrorBP: errorBP,
|
||||
Description: "Symmetry violation: reciprocal prices don't multiply to 1",
|
||||
}
|
||||
result.Failures = append(result.Failures, failure)
|
||||
result.FailCount++
|
||||
} else {
|
||||
result.PassCount++
|
||||
}
|
||||
|
||||
if errorBP > result.MaxError {
|
||||
result.MaxError = errorBP
|
||||
}
|
||||
}
|
||||
|
||||
if result.TestCount > 0 {
|
||||
result.AvgError = totalError / float64(result.TestCount)
|
||||
}
|
||||
result.Duration = time.Since(startTime)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// TestBoundaryProperties tests behavior at boundaries
|
||||
func (pts *PropertyTestSuite) TestBoundaryProperties(ctx context.Context, testCount int) (*PropertyTestResult, error) {
|
||||
startTime := time.Now()
|
||||
result := &PropertyTestResult{
|
||||
PropertyName: "Boundary Properties",
|
||||
TestCount: testCount,
|
||||
}
|
||||
|
||||
boundaryValues := []*big.Int{
|
||||
big.NewInt(1), // Minimum
|
||||
big.NewInt(1000), // Small
|
||||
new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil), // 1 token
|
||||
new(big.Int).Exp(big.NewInt(10), big.NewInt(21), nil), // 1000 tokens
|
||||
new(big.Int).Exp(big.NewInt(10), big.NewInt(25), nil), // Large value
|
||||
}
|
||||
|
||||
for i := 0; i < testCount; i++ {
|
||||
// Test combinations of boundary values
|
||||
reserve0 := boundaryValues[pts.rand.Intn(len(boundaryValues))]
|
||||
reserve1 := boundaryValues[pts.rand.Intn(len(boundaryValues))]
|
||||
|
||||
// Skip if reserves are equal to zero
|
||||
if reserve0.Cmp(big.NewInt(0)) == 0 || reserve1.Cmp(big.NewInt(0)) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
price, err := pts.auditor.calculateUniswapV2Price(
|
||||
&pkgmath.UniversalDecimal{Value: reserve0, Decimals: 18, Symbol: "TOKEN0"},
|
||||
&pkgmath.UniversalDecimal{Value: reserve1, Decimals: 18, Symbol: "TOKEN1"},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
failure := &PropertyFailure{
|
||||
Input: fmt.Sprintf("Reserve0: %s, Reserve1: %s", reserve0.String(), reserve1.String()),
|
||||
Expected: "Valid price calculation",
|
||||
Actual: fmt.Sprintf("Error: %v", err),
|
||||
ErrorBP: 10000.0,
|
||||
Description: "Boundary value calculation failed",
|
||||
}
|
||||
result.Failures = append(result.Failures, failure)
|
||||
result.FailCount++
|
||||
} else if price == nil || price.Value.Cmp(big.NewInt(0)) <= 0 {
|
||||
failure := &PropertyFailure{
|
||||
Input: fmt.Sprintf("Reserve0: %s, Reserve1: %s", reserve0.String(), reserve1.String()),
|
||||
Expected: "Positive price",
|
||||
Actual: "Zero or negative price",
|
||||
ErrorBP: 10000.0,
|
||||
Description: "Boundary value produced invalid price",
|
||||
}
|
||||
result.Failures = append(result.Failures, failure)
|
||||
result.FailCount++
|
||||
} else {
|
||||
result.PassCount++
|
||||
}
|
||||
}
|
||||
|
||||
result.Duration = time.Since(startTime)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// TestArithmeticProperties tests arithmetic operation properties
|
||||
func (pts *PropertyTestSuite) TestArithmeticProperties(ctx context.Context, testCount int) (*PropertyTestResult, error) {
|
||||
startTime := time.Now()
|
||||
result := &PropertyTestResult{
|
||||
PropertyName: "Arithmetic Properties",
|
||||
TestCount: testCount,
|
||||
}
|
||||
|
||||
var totalError float64
|
||||
|
||||
for i := 0; i < testCount; i++ {
|
||||
// Test that addition is commutative: a + b = b + a
|
||||
a := pts.generateRandomAmount()
|
||||
b := pts.generateRandomAmount()
|
||||
|
||||
decimalA, _ := pkgmath.NewUniversalDecimal(a, 18, "TOKENA")
|
||||
decimalB, _ := pkgmath.NewUniversalDecimal(b, 18, "TOKENB")
|
||||
|
||||
// Calculate a + b
|
||||
sum1 := new(big.Int).Add(decimalA.Value, decimalB.Value)
|
||||
|
||||
// Calculate b + a
|
||||
sum2 := new(big.Int).Add(decimalB.Value, decimalA.Value)
|
||||
|
||||
if sum1.Cmp(sum2) != 0 {
|
||||
failure := &PropertyFailure{
|
||||
Input: fmt.Sprintf("A: %s, B: %s", a.String(), b.String()),
|
||||
Expected: sum1.String(),
|
||||
Actual: sum2.String(),
|
||||
ErrorBP: 10000.0,
|
||||
Description: "Addition is not commutative",
|
||||
}
|
||||
result.Failures = append(result.Failures, failure)
|
||||
result.FailCount++
|
||||
totalError += 10000.0
|
||||
} else {
|
||||
result.PassCount++
|
||||
}
|
||||
}
|
||||
|
||||
if result.TestCount > 0 {
|
||||
result.AvgError = totalError / float64(result.TestCount)
|
||||
}
|
||||
result.Duration = time.Since(startTime)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Helper functions for generating test data
|
||||
|
||||
func (pts *PropertyTestSuite) generateRandomPrice() float64 {
|
||||
// Generate prices between 0.000001 and 1000000
|
||||
exponent := pts.rand.Float64()*12 - 6 // -6 to 6
|
||||
return stdmath.Pow(10, exponent)
|
||||
}
|
||||
|
||||
func (pts *PropertyTestSuite) generateRandomReserve() *big.Int {
|
||||
// Generate reserves between 1 and 10^25
|
||||
exp := pts.rand.Intn(25) + 1
|
||||
base := big.NewInt(int64(pts.rand.Intn(9) + 1))
|
||||
return new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(exp)), nil).Mul(base, new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(exp)), nil))
|
||||
}
|
||||
|
||||
func (pts *PropertyTestSuite) generateRandomAmount() *big.Int {
|
||||
// Generate amounts between 1 and 10^24
|
||||
exp := pts.rand.Intn(24) + 1
|
||||
base := big.NewInt(int64(pts.rand.Intn(9) + 1))
|
||||
return new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(exp)), nil).Mul(base, new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(exp)), nil))
|
||||
}
|
||||
97
orig/tools/math-audit/internal/report/report.go
Normal file
97
orig/tools/math-audit/internal/report/report.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package report
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal/audit"
|
||||
)
|
||||
|
||||
// WriteJSON writes the audit result as pretty JSON to the specified directory.
|
||||
func WriteJSON(dir string, res audit.Result) (string, error) {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", fmt.Errorf("create report dir: %w", err)
|
||||
}
|
||||
path := filepath.Join(dir, "report.json")
|
||||
payload, err := json.MarshalIndent(res, "", " ")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal report: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(path, payload, 0o644); err != nil {
|
||||
return "", fmt.Errorf("write report: %w", err)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// WriteMarkdown renders a human-readable summary and writes it next to the JSON.
|
||||
func WriteMarkdown(dir string, res audit.Result) (string, error) {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", fmt.Errorf("create report dir: %w", err)
|
||||
}
|
||||
path := filepath.Join(dir, "report.md")
|
||||
content := GenerateMarkdown(res)
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
return "", fmt.Errorf("write markdown: %w", err)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// GenerateMarkdown returns a markdown representation of the audit result.
|
||||
func GenerateMarkdown(res audit.Result) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("# Math Audit Report\n\n")
|
||||
b.WriteString(fmt.Sprintf("- Generated: %s UTC\n", res.Summary.GeneratedAt.Format("2006-01-02 15:04:05")))
|
||||
b.WriteString(fmt.Sprintf("- Vectors: %d/%d passed\n", res.Summary.VectorsPassed, res.Summary.TotalVectors))
|
||||
b.WriteString(fmt.Sprintf("- Assertions: %d/%d passed\n", res.Summary.AssertionsPassed, res.Summary.TotalAssertions))
|
||||
b.WriteString(fmt.Sprintf("- Property checks: %d/%d passed\n\n", res.Summary.PropertySucceeded, res.Summary.PropertyChecks))
|
||||
|
||||
if len(res.Vectors) > 0 {
|
||||
b.WriteString("## Vector Results\n\n")
|
||||
b.WriteString("| Vector | Exchange | Status | Notes |\n")
|
||||
b.WriteString("| --- | --- | --- | --- |\n")
|
||||
for _, vec := range res.Vectors {
|
||||
status := "✅ PASS"
|
||||
if !vec.Passed {
|
||||
status = "❌ FAIL"
|
||||
}
|
||||
|
||||
var notes []string
|
||||
for _, test := range vec.Tests {
|
||||
if !test.Passed {
|
||||
notes = append(notes, fmt.Sprintf("%s (%.4f bps)", test.Name, test.DeltaBPS))
|
||||
}
|
||||
}
|
||||
if len(vec.Errors) > 0 {
|
||||
notes = append(notes, vec.Errors...)
|
||||
}
|
||||
noteStr := ""
|
||||
if len(notes) > 0 {
|
||||
noteStr = strings.Join(notes, "; ")
|
||||
}
|
||||
|
||||
b.WriteString(fmt.Sprintf("| %s | %s | %s | %s |\n", vec.Name, vec.Exchange, status, noteStr))
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
if len(res.PropertyChecks) > 0 {
|
||||
b.WriteString("## Property Checks\n\n")
|
||||
for _, check := range res.PropertyChecks {
|
||||
status := "✅"
|
||||
if !check.Passed {
|
||||
status = "❌"
|
||||
}
|
||||
if check.Details != "" {
|
||||
b.WriteString(fmt.Sprintf("- %s %s — %s\n", status, check.Name, check.Details))
|
||||
} else {
|
||||
b.WriteString(fmt.Sprintf("- %s %s\n", status, check.Name))
|
||||
}
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
202
orig/tools/math-audit/internal/reports.go
Normal file
202
orig/tools/math-audit/internal/reports.go
Normal file
@@ -0,0 +1,202 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// GenerateMarkdownReport creates a comprehensive markdown report
|
||||
func GenerateMarkdownReport(report *ComprehensiveAuditReport) string {
|
||||
var sb strings.Builder
|
||||
|
||||
// Header
|
||||
sb.WriteString("# MEV Bot Math Audit Report\n\n")
|
||||
sb.WriteString(fmt.Sprintf("**Generated:** %s\n", report.Timestamp.Format(time.RFC3339)))
|
||||
sb.WriteString(fmt.Sprintf("**Test Vectors:** %s\n", report.VectorsFile))
|
||||
sb.WriteString(fmt.Sprintf("**Error Tolerance:** %.1f basis points\n\n", report.ToleranceBP))
|
||||
|
||||
// Executive Summary
|
||||
sb.WriteString("## Executive Summary\n\n")
|
||||
status := "✅ PASS"
|
||||
if !report.OverallPassed {
|
||||
status = "❌ FAIL"
|
||||
}
|
||||
sb.WriteString(fmt.Sprintf("**Overall Status:** %s\n\n", status))
|
||||
|
||||
sb.WriteString("### Summary Statistics\n\n")
|
||||
sb.WriteString("| Metric | Value |\n")
|
||||
sb.WriteString("|--------|-------|\n")
|
||||
sb.WriteString(fmt.Sprintf("| Total Tests | %d |\n", report.TotalTests))
|
||||
sb.WriteString(fmt.Sprintf("| Passed Tests | %d |\n", report.TotalPassed))
|
||||
sb.WriteString(fmt.Sprintf("| Failed Tests | %d |\n", report.TotalFailed))
|
||||
successRate := 0.0
|
||||
if report.TotalTests > 0 {
|
||||
successRate = float64(report.TotalPassed) / float64(report.TotalTests) * 100
|
||||
}
|
||||
sb.WriteString(fmt.Sprintf("| Success Rate | %.2f%% |\n", successRate))
|
||||
sb.WriteString(fmt.Sprintf("| Exchanges Tested | %d |\n\n", len(report.ExchangeResults)))
|
||||
|
||||
// Exchange Results
|
||||
sb.WriteString("## Exchange Results\n\n")
|
||||
|
||||
for exchangeType, result := range report.ExchangeResults {
|
||||
sb.WriteString(fmt.Sprintf("### %s\n\n", strings.ToUpper(exchangeType)))
|
||||
|
||||
exchangeStatus := "✅ PASS"
|
||||
if result.FailedTests > 0 {
|
||||
exchangeStatus = "❌ FAIL"
|
||||
}
|
||||
sb.WriteString(fmt.Sprintf("**Status:** %s\n", exchangeStatus))
|
||||
sb.WriteString(fmt.Sprintf("**Duration:** %v\n\n", result.Duration.Round(time.Millisecond)))
|
||||
|
||||
// Exchange statistics
|
||||
sb.WriteString("#### Test Statistics\n\n")
|
||||
sb.WriteString("| Metric | Value |\n")
|
||||
sb.WriteString("|--------|-------|\n")
|
||||
sb.WriteString(fmt.Sprintf("| Total Tests | %d |\n", result.TotalTests))
|
||||
sb.WriteString(fmt.Sprintf("| Passed | %d |\n", result.PassedTests))
|
||||
sb.WriteString(fmt.Sprintf("| Failed | %d |\n", result.FailedTests))
|
||||
sb.WriteString(fmt.Sprintf("| Max Error | %.4f bp |\n", result.MaxErrorBP))
|
||||
sb.WriteString(fmt.Sprintf("| Avg Error | %.4f bp |\n", result.AvgErrorBP))
|
||||
|
||||
// Failed cases
|
||||
if len(result.FailedCases) > 0 {
|
||||
sb.WriteString("\n#### Failed Test Cases\n\n")
|
||||
sb.WriteString("| Test Name | Error (bp) | Description |\n")
|
||||
sb.WriteString("|-----------|------------|-------------|\n")
|
||||
|
||||
for _, failure := range result.FailedCases {
|
||||
sb.WriteString(fmt.Sprintf("| %s | %.4f | %s |\n",
|
||||
failure.TestName, failure.ErrorBP, failure.Description))
|
||||
}
|
||||
}
|
||||
|
||||
// Test breakdown by category
|
||||
sb.WriteString("\n#### Test Breakdown\n\n")
|
||||
pricingTests := 0
|
||||
amountTests := 0
|
||||
priceImpactTests := 0
|
||||
|
||||
for _, testResult := range result.TestResults {
|
||||
if strings.Contains(strings.ToLower(testResult.Description), "pricing") {
|
||||
pricingTests++
|
||||
} else if strings.Contains(strings.ToLower(testResult.Description), "amount") {
|
||||
amountTests++
|
||||
} else if strings.Contains(strings.ToLower(testResult.Description), "price impact") {
|
||||
priceImpactTests++
|
||||
}
|
||||
}
|
||||
|
||||
sb.WriteString("| Category | Tests |\n")
|
||||
sb.WriteString("|----------|-------|\n")
|
||||
sb.WriteString(fmt.Sprintf("| Pricing Functions | %d |\n", pricingTests))
|
||||
sb.WriteString(fmt.Sprintf("| Amount Calculations | %d |\n", amountTests))
|
||||
sb.WriteString(fmt.Sprintf("| Price Impact | %d |\n", priceImpactTests))
|
||||
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
|
||||
// Detailed Test Results
|
||||
if !report.OverallPassed {
|
||||
sb.WriteString("## Detailed Failure Analysis\n\n")
|
||||
|
||||
for exchangeType, result := range report.ExchangeResults {
|
||||
if result.FailedTests == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
sb.WriteString(fmt.Sprintf("### %s Failures\n\n", strings.ToUpper(exchangeType)))
|
||||
|
||||
for _, failure := range result.FailedCases {
|
||||
sb.WriteString(fmt.Sprintf("#### %s\n\n", failure.TestName))
|
||||
sb.WriteString(fmt.Sprintf("**Error:** %.4f basis points\n", failure.ErrorBP))
|
||||
sb.WriteString(fmt.Sprintf("**Description:** %s\n", failure.Description))
|
||||
|
||||
if failure.Expected != "" && failure.Actual != "" {
|
||||
sb.WriteString(fmt.Sprintf("**Expected:** %s\n", failure.Expected))
|
||||
sb.WriteString(fmt.Sprintf("**Actual:** %s\n", failure.Actual))
|
||||
}
|
||||
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recommendations
|
||||
sb.WriteString("## Recommendations\n\n")
|
||||
|
||||
if report.OverallPassed {
|
||||
sb.WriteString("✅ All mathematical validations passed successfully.\n\n")
|
||||
sb.WriteString("### Next Steps\n\n")
|
||||
sb.WriteString("- Consider running extended test vectors for comprehensive validation\n")
|
||||
sb.WriteString("- Implement continuous mathematical validation in CI/CD pipeline\n")
|
||||
sb.WriteString("- Monitor for precision degradation with production data\n")
|
||||
} else {
|
||||
sb.WriteString("❌ Mathematical validation failures detected.\n\n")
|
||||
sb.WriteString("### Critical Actions Required\n\n")
|
||||
|
||||
// Prioritize recommendations based on error severity
|
||||
for exchangeType, result := range report.ExchangeResults {
|
||||
if result.FailedTests == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if result.MaxErrorBP > 100 { // > 1%
|
||||
sb.WriteString(fmt.Sprintf("- **CRITICAL**: Fix %s calculations (max error: %.2f%%)\n",
|
||||
exchangeType, result.MaxErrorBP/100))
|
||||
} else if result.MaxErrorBP > 10 { // > 0.1%
|
||||
sb.WriteString(fmt.Sprintf("- **HIGH**: Review %s precision (max error: %.2f basis points)\n",
|
||||
exchangeType, result.MaxErrorBP))
|
||||
} else {
|
||||
sb.WriteString(fmt.Sprintf("- **MEDIUM**: Fine-tune %s calculations (max error: %.2f basis points)\n",
|
||||
exchangeType, result.MaxErrorBP))
|
||||
}
|
||||
}
|
||||
|
||||
sb.WriteString("\n### General Recommendations\n\n")
|
||||
sb.WriteString("- Review mathematical formulas against canonical implementations\n")
|
||||
sb.WriteString("- Verify decimal precision handling in UniversalDecimal\n")
|
||||
sb.WriteString("- Add unit tests for edge cases discovered in this audit\n")
|
||||
sb.WriteString("- Consider using higher precision arithmetic for critical calculations\n")
|
||||
}
|
||||
|
||||
// Footer
|
||||
sb.WriteString("\n---\n\n")
|
||||
sb.WriteString("*This report was generated by the MEV Bot Math Audit Tool*\n")
|
||||
sb.WriteString(fmt.Sprintf("*Report generated at: %s*\n", time.Now().Format(time.RFC3339)))
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// GenerateJSONSummary creates a concise JSON summary for programmatic use
|
||||
func GenerateJSONSummary(report *ComprehensiveAuditReport) map[string]interface{} {
|
||||
summary := map[string]interface{}{
|
||||
"overall_status": report.OverallPassed,
|
||||
"total_tests": report.TotalTests,
|
||||
"total_passed": report.TotalPassed,
|
||||
"total_failed": report.TotalFailed,
|
||||
"success_rate": float64(report.TotalPassed) / float64(report.TotalTests) * 100,
|
||||
"timestamp": report.Timestamp,
|
||||
"vectors_file": report.VectorsFile,
|
||||
"tolerance_bp": report.ToleranceBP,
|
||||
"exchange_count": len(report.ExchangeResults),
|
||||
}
|
||||
|
||||
// Exchange summaries
|
||||
exchanges := make(map[string]interface{})
|
||||
for exchangeType, result := range report.ExchangeResults {
|
||||
exchanges[exchangeType] = map[string]interface{}{
|
||||
"status": result.FailedTests == 0,
|
||||
"total_tests": result.TotalTests,
|
||||
"passed_tests": result.PassedTests,
|
||||
"failed_tests": result.FailedTests,
|
||||
"max_error_bp": result.MaxErrorBP,
|
||||
"avg_error_bp": result.AvgErrorBP,
|
||||
"duration_ms": result.Duration.Milliseconds(),
|
||||
}
|
||||
}
|
||||
summary["exchanges"] = exchanges
|
||||
|
||||
return summary
|
||||
}
|
||||
254
orig/tools/math-audit/internal/vectors.go
Normal file
254
orig/tools/math-audit/internal/vectors.go
Normal file
@@ -0,0 +1,254 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// TestVectors contains all test vectors for mathematical validation
|
||||
type TestVectors struct {
|
||||
Version string `json:"version"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Exchanges map[string]*ExchangeVectors `json:"exchanges"`
|
||||
}
|
||||
|
||||
// ExchangeVectors contains test vectors for a specific exchange
|
||||
type ExchangeVectors struct {
|
||||
ExchangeType string `json:"exchange_type"`
|
||||
PricingTests []*PricingTest `json:"pricing_tests"`
|
||||
AmountTests []*AmountTest `json:"amount_tests"`
|
||||
PriceImpactTests []*PriceImpactTest `json:"price_impact_tests"`
|
||||
}
|
||||
|
||||
// PricingTest represents a test case for price calculation
|
||||
type PricingTest struct {
|
||||
TestName string `json:"test_name"`
|
||||
Description string `json:"description"`
|
||||
Reserve0 string `json:"reserve_0"`
|
||||
Reserve1 string `json:"reserve_1"`
|
||||
Fee string `json:"fee,omitempty"`
|
||||
SqrtPriceX96 string `json:"sqrt_price_x96,omitempty"`
|
||||
Tick int `json:"tick,omitempty"`
|
||||
ExpectedPrice string `json:"expected_price"`
|
||||
Tolerance float64 `json:"tolerance"` // Basis points
|
||||
}
|
||||
|
||||
// AmountTest represents a test case for amount in/out calculations
|
||||
type AmountTest struct {
|
||||
TestName string `json:"test_name"`
|
||||
Description string `json:"description"`
|
||||
Reserve0 string `json:"reserve_0"`
|
||||
Reserve1 string `json:"reserve_1"`
|
||||
AmountIn string `json:"amount_in"`
|
||||
TokenIn string `json:"token_in"` // "0" or "1"
|
||||
Fee string `json:"fee,omitempty"`
|
||||
ExpectedAmountOut string `json:"expected_amount_out"`
|
||||
Tolerance float64 `json:"tolerance"` // Basis points
|
||||
}
|
||||
|
||||
// PriceImpactTest represents a test case for price impact calculations
|
||||
type PriceImpactTest struct {
|
||||
TestName string `json:"test_name"`
|
||||
Description string `json:"description"`
|
||||
Reserve0 string `json:"reserve_0"`
|
||||
Reserve1 string `json:"reserve_1"`
|
||||
SwapAmount string `json:"swap_amount"`
|
||||
TokenIn string `json:"token_in"` // "0" or "1"
|
||||
ExpectedPriceImpact string `json:"expected_price_impact"` // Percentage
|
||||
Tolerance float64 `json:"tolerance"` // Basis points
|
||||
}
|
||||
|
||||
// LoadTestVectors loads test vectors from file or preset
|
||||
func LoadTestVectors(source string) (*TestVectors, error) {
|
||||
switch source {
|
||||
case "default":
|
||||
return loadDefaultVectors()
|
||||
case "comprehensive":
|
||||
return loadComprehensiveVectors()
|
||||
default:
|
||||
// Try to load from file
|
||||
return loadVectorsFromFile(source)
|
||||
}
|
||||
}
|
||||
|
||||
// GetExchangeVectors returns vectors for a specific exchange
|
||||
func (tv *TestVectors) GetExchangeVectors(exchangeType string) *ExchangeVectors {
|
||||
return tv.Exchanges[exchangeType]
|
||||
}
|
||||
|
||||
// loadDefaultVectors returns a basic set of test vectors
|
||||
func loadDefaultVectors() (*TestVectors, error) {
|
||||
vectors := &TestVectors{
|
||||
Version: "1.0.0",
|
||||
Timestamp: "2024-10-08T00:00:00Z",
|
||||
Exchanges: make(map[string]*ExchangeVectors),
|
||||
}
|
||||
|
||||
// Uniswap V2 test vectors
|
||||
vectors.Exchanges["uniswap_v2"] = &ExchangeVectors{
|
||||
ExchangeType: "uniswap_v2",
|
||||
PricingTests: []*PricingTest{
|
||||
{
|
||||
TestName: "ETH_USDC_Basic",
|
||||
Description: "Basic ETH/USDC price calculation",
|
||||
Reserve0: "1000000000000000000000", // 1000 ETH
|
||||
Reserve1: "2000000000000", // 2M USDC
|
||||
ExpectedPrice: "2000000000000000000000", // 2000 USDC per ETH
|
||||
Tolerance: 1.0, // 1 bp
|
||||
},
|
||||
{
|
||||
TestName: "WBTC_ETH_Basic",
|
||||
Description: "Basic WBTC/ETH price calculation",
|
||||
Reserve0: "50000000000", // 500 WBTC (8 decimals)
|
||||
Reserve1: "10000000000000000000000", // 10000 ETH
|
||||
ExpectedPrice: "20000000000000000000", // 20 ETH per WBTC
|
||||
Tolerance: 1.0,
|
||||
},
|
||||
},
|
||||
AmountTests: []*AmountTest{
|
||||
{
|
||||
TestName: "ETH_to_USDC_Swap",
|
||||
Description: "1 ETH to USDC swap",
|
||||
Reserve0: "1000000000000000000000", // 1000 ETH
|
||||
Reserve1: "2000000000000", // 2M USDC
|
||||
AmountIn: "1000000000000000000", // 1 ETH
|
||||
TokenIn: "0",
|
||||
Fee: "3000", // 0.3%
|
||||
ExpectedAmountOut: "1994006985000", // ~1994 USDC after fees
|
||||
Tolerance: 5.0, // 5 bp
|
||||
},
|
||||
},
|
||||
PriceImpactTests: []*PriceImpactTest{
|
||||
{
|
||||
TestName: "Large_ETH_Swap_Impact",
|
||||
Description: "Price impact of 100 ETH swap",
|
||||
Reserve0: "1000000000000000000000", // 1000 ETH
|
||||
Reserve1: "2000000000000", // 2M USDC
|
||||
SwapAmount: "100000000000000000000", // 100 ETH
|
||||
TokenIn: "0",
|
||||
ExpectedPriceImpact: "9.09", // ~9.09% price impact
|
||||
Tolerance: 10.0, // 10 bp
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Uniswap V3 test vectors
|
||||
vectors.Exchanges["uniswap_v3"] = &ExchangeVectors{
|
||||
ExchangeType: "uniswap_v3",
|
||||
PricingTests: []*PricingTest{
|
||||
{
|
||||
TestName: "ETH_USDC_V3_Basic",
|
||||
Description: "Basic ETH/USDC V3 price from sqrtPriceX96",
|
||||
SqrtPriceX96: "3543191142285914327220224", // ~2000 USDC per ETH (corrected)
|
||||
ExpectedPrice: "2000000000000000000000",
|
||||
Tolerance: 1.0,
|
||||
},
|
||||
},
|
||||
AmountTests: []*AmountTest{
|
||||
{
|
||||
TestName: "V3_Concentrated_Liquidity",
|
||||
Description: "Swap within concentrated liquidity range",
|
||||
Reserve0: "1000000000000000000000",
|
||||
Reserve1: "2000000000000",
|
||||
AmountIn: "1000000000000000000",
|
||||
TokenIn: "0",
|
||||
Fee: "500", // 0.05%
|
||||
ExpectedAmountOut: "1999000000000",
|
||||
Tolerance: 2.0,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Add more exchanges...
|
||||
vectors.Exchanges["curve"] = createCurveVectors()
|
||||
vectors.Exchanges["balancer"] = createBalancerVectors()
|
||||
|
||||
return vectors, nil
|
||||
}
|
||||
|
||||
// loadComprehensiveVectors returns extensive test vectors
|
||||
func loadComprehensiveVectors() (*TestVectors, error) {
|
||||
// This would load a much more comprehensive set of test vectors
|
||||
// For now, return the default set
|
||||
return loadDefaultVectors()
|
||||
}
|
||||
|
||||
// loadVectorsFromFile loads test vectors from a JSON file
|
||||
func loadVectorsFromFile(filename string) (*TestVectors, error) {
|
||||
// Check if it's a relative path within vectors directory
|
||||
if !filepath.IsAbs(filename) {
|
||||
filename = filepath.Join("vectors", filename+".json")
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read vectors file %s: %w", filename, err)
|
||||
}
|
||||
|
||||
var vectors TestVectors
|
||||
if err := json.Unmarshal(data, &vectors); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse vectors file %s: %w", filename, err)
|
||||
}
|
||||
|
||||
return &vectors, nil
|
||||
}
|
||||
|
||||
// createCurveVectors creates test vectors for Curve pools
|
||||
func createCurveVectors() *ExchangeVectors {
|
||||
return &ExchangeVectors{
|
||||
ExchangeType: "curve",
|
||||
PricingTests: []*PricingTest{
|
||||
{
|
||||
TestName: "Stable_USDC_USDT",
|
||||
Description: "Stable swap USDC/USDT pricing",
|
||||
Reserve0: "1000000000000", // 1M USDC
|
||||
Reserve1: "1000000000000", // 1M USDT
|
||||
ExpectedPrice: "1000000000000000000", // 1:1 ratio
|
||||
Tolerance: 0.5,
|
||||
},
|
||||
},
|
||||
AmountTests: []*AmountTest{
|
||||
{
|
||||
TestName: "Stable_Swap_Low_Impact",
|
||||
Description: "Low price impact stable swap",
|
||||
Reserve0: "1000000000000",
|
||||
Reserve1: "1000000000000",
|
||||
AmountIn: "1000000000", // 1000 USDC
|
||||
TokenIn: "0",
|
||||
ExpectedAmountOut: "999000000", // ~999 USDT after fees
|
||||
Tolerance: 1.0,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// createBalancerVectors creates test vectors for Balancer pools
|
||||
func createBalancerVectors() *ExchangeVectors {
|
||||
return &ExchangeVectors{
|
||||
ExchangeType: "balancer",
|
||||
PricingTests: []*PricingTest{
|
||||
{
|
||||
TestName: "Weighted_80_20_Pool",
|
||||
Description: "80/20 weighted pool pricing",
|
||||
Reserve0: "800000000000000000000", // 800 ETH (80%)
|
||||
Reserve1: "400000000000", // 400k USDC (20%)
|
||||
ExpectedPrice: "2000000000000000000000", // 2000 USDC per ETH (corrected)
|
||||
Tolerance: 2.0,
|
||||
},
|
||||
},
|
||||
AmountTests: []*AmountTest{
|
||||
{
|
||||
TestName: "Weighted_Pool_Swap",
|
||||
Description: "Swap in weighted pool",
|
||||
Reserve0: "800000000000000000000",
|
||||
Reserve1: "400000000000",
|
||||
AmountIn: "1000000000000000000", // 1 ETH
|
||||
TokenIn: "0",
|
||||
ExpectedAmountOut: "2475000000000", // ~2475 USDC
|
||||
Tolerance: 5.0,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
66
orig/tools/math-audit/main.go
Normal file
66
orig/tools/math-audit/main.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal/audit"
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal/checks"
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal/loader"
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal/report"
|
||||
)
|
||||
|
||||
var (
|
||||
vectorsFlag = flag.String("vectors", "default", "Vector set to load (default, path, or comma-separated list)")
|
||||
reportDir = flag.String("report", "", "Optional directory to write JSON and Markdown reports")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
log.SetFlags(0)
|
||||
|
||||
vectors, err := loader.LoadVectors(*vectorsFlag)
|
||||
if err != nil {
|
||||
log.Fatalf("load vectors: %v", err)
|
||||
}
|
||||
|
||||
if len(vectors) == 0 {
|
||||
log.Fatalf("no vectors loaded from selector %q", *vectorsFlag)
|
||||
}
|
||||
|
||||
runner := audit.NewRunner()
|
||||
propertyChecks := checks.Run()
|
||||
result := runner.Run(vectors, propertyChecks)
|
||||
|
||||
failed := (result.Summary.VectorsPassed != result.Summary.TotalVectors) ||
|
||||
(result.Summary.AssertionsPassed != result.Summary.TotalAssertions) ||
|
||||
(result.Summary.PropertySucceeded != result.Summary.PropertyChecks)
|
||||
|
||||
fmt.Printf("Math audit completed: %d/%d vectors passed, %d/%d assertions passed, %d/%d property checks succeeded\n",
|
||||
result.Summary.VectorsPassed,
|
||||
result.Summary.TotalVectors,
|
||||
result.Summary.AssertionsPassed,
|
||||
result.Summary.TotalAssertions,
|
||||
result.Summary.PropertySucceeded,
|
||||
result.Summary.PropertyChecks,
|
||||
)
|
||||
|
||||
if *reportDir != "" {
|
||||
jsonPath, err := report.WriteJSON(*reportDir, result)
|
||||
if err != nil {
|
||||
log.Fatalf("write json report: %v", err)
|
||||
}
|
||||
mdPath, err := report.WriteMarkdown(*reportDir, result)
|
||||
if err != nil {
|
||||
log.Fatalf("write markdown report: %v", err)
|
||||
}
|
||||
fmt.Printf("Reports written to %s and %s\n", jsonPath, mdPath)
|
||||
}
|
||||
|
||||
if failed {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
BIN
orig/tools/math-audit/math-audit-tool
Executable file
BIN
orig/tools/math-audit/math-audit-tool
Executable file
Binary file not shown.
404
orig/tools/math-audit/profit_regression_test.go
Normal file
404
orig/tools/math-audit/profit_regression_test.go
Normal file
@@ -0,0 +1,404 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"testing"
|
||||
|
||||
pkgmath "github.com/fraktal/mev-beta/pkg/math"
|
||||
"github.com/fraktal/mev-beta/tools/math-audit/internal"
|
||||
)
|
||||
|
||||
// ProfitRegressionTestCase defines a test case for profit regression validation
|
||||
type ProfitRegressionTestCase struct {
|
||||
Name string
|
||||
Exchange string
|
||||
TestData *internal.PricingTest
|
||||
ExpectedProfit float64 // Expected profit margin in basis points
|
||||
MinProfit float64 // Minimum acceptable profit in basis points
|
||||
MaxProfit float64 // Maximum acceptable profit in basis points
|
||||
Description string
|
||||
}
|
||||
|
||||
// TestProfitRegressionValidation tests that profit calculations remain within expected ranges
|
||||
func TestProfitRegressionValidation(t *testing.T) {
|
||||
converter := pkgmath.NewDecimalConverter()
|
||||
auditor := internal.NewMathAuditor(converter, 0.0001) // 1bp tolerance
|
||||
|
||||
testCases := []ProfitRegressionTestCase{
|
||||
{
|
||||
Name: "Uniswap_V2_ETH_USDC_Precision",
|
||||
Exchange: "uniswap_v2",
|
||||
TestData: &internal.PricingTest{
|
||||
TestName: "ETH_USDC_Standard_Pool",
|
||||
Description: "Standard ETH/USDC pool price calculation",
|
||||
Reserve0: "1000000000000000000000", // 1000 ETH
|
||||
Reserve1: "2000000000000", // 2M USDC
|
||||
ExpectedPrice: "2000000000000000000000", // 2000 USDC per ETH
|
||||
Tolerance: 1.0,
|
||||
},
|
||||
ExpectedProfit: 0.0, // Perfect pricing should have 0 profit difference
|
||||
MinProfit: -5.0, // Allow 5bp negative
|
||||
MaxProfit: 5.0, // Allow 5bp positive
|
||||
Description: "Validates Uniswap V2 pricing precision for profit calculations",
|
||||
},
|
||||
{
|
||||
Name: "Uniswap_V3_ETH_USDC_Precision",
|
||||
Exchange: "uniswap_v3",
|
||||
TestData: &internal.PricingTest{
|
||||
TestName: "ETH_USDC_V3_Basic",
|
||||
Description: "ETH/USDC V3 price from sqrtPriceX96",
|
||||
SqrtPriceX96: "3543191142285914327220224", // Corrected value
|
||||
ExpectedPrice: "2000000000000000000000", // 2000 USDC per ETH
|
||||
Tolerance: 1.0,
|
||||
},
|
||||
ExpectedProfit: 0.0, // Perfect pricing should have 0 profit difference
|
||||
MinProfit: -5.0, // Allow 5bp negative
|
||||
MaxProfit: 5.0, // Allow 5bp positive
|
||||
Description: "Validates Uniswap V3 pricing precision for profit calculations",
|
||||
},
|
||||
{
|
||||
Name: "Curve_USDC_USDT_Stable_Precision",
|
||||
Exchange: "curve",
|
||||
TestData: &internal.PricingTest{
|
||||
TestName: "Stable_USDC_USDT",
|
||||
Description: "Stable swap USDC/USDT pricing",
|
||||
Reserve0: "1000000000000", // 1M USDC
|
||||
Reserve1: "1000000000000", // 1M USDT
|
||||
ExpectedPrice: "1000000000000000000", // 1:1 ratio
|
||||
Tolerance: 0.5,
|
||||
},
|
||||
ExpectedProfit: 0.0, // Stable swaps should have minimal profit difference
|
||||
MinProfit: -2.0, // Allow 2bp negative
|
||||
MaxProfit: 2.0, // Allow 2bp positive
|
||||
Description: "Validates Curve stable swap pricing precision",
|
||||
},
|
||||
{
|
||||
Name: "Balancer_80_20_Weighted_Precision",
|
||||
Exchange: "balancer",
|
||||
TestData: &internal.PricingTest{
|
||||
TestName: "Weighted_80_20_Pool",
|
||||
Description: "80/20 weighted pool pricing",
|
||||
Reserve0: "800000000000000000000", // 800 ETH
|
||||
Reserve1: "400000000000", // 400k USDC
|
||||
ExpectedPrice: "2000000000000000000000", // 2000 USDC per ETH (corrected)
|
||||
Tolerance: 2.0,
|
||||
},
|
||||
ExpectedProfit: 0.0, // Proper weighted calculation should be precise
|
||||
MinProfit: -10.0, // Allow 10bp negative for weighted pools
|
||||
MaxProfit: 10.0, // Allow 10bp positive for weighted pools
|
||||
Description: "Validates Balancer weighted pool pricing precision",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
// Run profit regression validation
|
||||
|
||||
// Run the pricing test using the auditor
|
||||
result := runPricingTestForProfit(auditor, tc.Exchange, tc.TestData)
|
||||
|
||||
// Calculate profit based on error
|
||||
profitBP := result.ErrorBP
|
||||
|
||||
// Validate profit is within expected range
|
||||
if profitBP < tc.MinProfit {
|
||||
t.Errorf("Profit %.4f bp below minimum threshold %.4f bp", profitBP, tc.MinProfit)
|
||||
}
|
||||
|
||||
if profitBP > tc.MaxProfit {
|
||||
t.Errorf("Profit %.4f bp above maximum threshold %.4f bp", profitBP, tc.MaxProfit)
|
||||
}
|
||||
|
||||
// Check if the test passed the original validation
|
||||
if !result.Passed {
|
||||
t.Errorf("Underlying pricing test failed with %.4f bp error", result.ErrorBP)
|
||||
}
|
||||
|
||||
t.Logf("✓ %s: Error=%.4f bp (expected ~%.4f bp, range: %.1f to %.1f bp)",
|
||||
tc.Name, profitBP, tc.ExpectedProfit, tc.MinProfit, tc.MaxProfit)
|
||||
t.Logf(" %s", tc.Description)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// runPricingTestForProfit runs a pricing test and returns the result for profit analysis
|
||||
func runPricingTestForProfit(auditor *internal.MathAuditor, exchangeType string, test *internal.PricingTest) *internal.IndividualTestResult {
|
||||
// This is a simplified version of the runPricingTest method from auditor.go
|
||||
// We use the same logic to ensure consistency
|
||||
|
||||
// Determine decimals based on test name patterns
|
||||
reserve0Decimals := uint8(18) // Default to 18 decimals
|
||||
reserve1Decimals := uint8(18) // Default to 18 decimals
|
||||
|
||||
if test.TestName == "ETH_USDC_Standard_Pool" || test.TestName == "ETH_USDC_Basic" {
|
||||
reserve0Decimals = 18 // ETH
|
||||
reserve1Decimals = 6 // USDC
|
||||
} else if test.TestName == "WBTC_ETH_High_Value" || test.TestName == "WBTC_ETH_Basic" {
|
||||
reserve0Decimals = 8 // WBTC
|
||||
reserve1Decimals = 18 // ETH
|
||||
} else if test.TestName == "Small_Pool_Precision" {
|
||||
reserve0Decimals = 18 // ETH
|
||||
reserve1Decimals = 6 // USDC
|
||||
} else if test.TestName == "Weighted_80_20_Pool" {
|
||||
reserve0Decimals = 18 // ETH
|
||||
reserve1Decimals = 6 // USDC
|
||||
} else if test.TestName == "Stable_USDC_USDT" {
|
||||
reserve0Decimals = 6 // USDC
|
||||
reserve1Decimals = 6 // USDT
|
||||
} else if test.TestName == "ETH_USDC_V3_Basic" {
|
||||
reserve0Decimals = 18 // ETH
|
||||
reserve1Decimals = 6 // USDC
|
||||
}
|
||||
|
||||
converter := pkgmath.NewDecimalConverter()
|
||||
|
||||
// Calculate price using the same methods as the auditor
|
||||
var calculatedPrice *pkgmath.UniversalDecimal
|
||||
var err error
|
||||
|
||||
switch exchangeType {
|
||||
case "uniswap_v2":
|
||||
reserve0, _ := converter.FromString(test.Reserve0, reserve0Decimals, "TOKEN0")
|
||||
reserve1, _ := converter.FromString(test.Reserve1, reserve1Decimals, "TOKEN1")
|
||||
calculatedPrice, err = calculateUniswapV2PriceForRegression(converter, reserve0, reserve1)
|
||||
case "uniswap_v3":
|
||||
calculatedPrice, err = calculateUniswapV3PriceForRegression(converter, test)
|
||||
case "curve":
|
||||
reserve0, _ := converter.FromString(test.Reserve0, reserve0Decimals, "TOKEN0")
|
||||
reserve1, _ := converter.FromString(test.Reserve1, reserve1Decimals, "TOKEN1")
|
||||
calculatedPrice, err = calculateCurvePriceForRegression(converter, reserve0, reserve1)
|
||||
case "balancer":
|
||||
reserve0, _ := converter.FromString(test.Reserve0, reserve0Decimals, "TOKEN0")
|
||||
reserve1, _ := converter.FromString(test.Reserve1, reserve1Decimals, "TOKEN1")
|
||||
calculatedPrice, err = calculateBalancerPriceForRegression(converter, reserve0, reserve1)
|
||||
default:
|
||||
err = fmt.Errorf("unknown exchange type: %s", exchangeType)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return &internal.IndividualTestResult{
|
||||
TestName: test.TestName,
|
||||
Passed: false,
|
||||
ErrorBP: 10000, // Max error
|
||||
Description: fmt.Sprintf("Calculation failed: %v", err),
|
||||
}
|
||||
}
|
||||
|
||||
// Compare with expected result
|
||||
expectedPrice, _ := converter.FromString(test.ExpectedPrice, 18, "PRICE")
|
||||
errorBP := calculateErrorBPForRegression(expectedPrice, calculatedPrice)
|
||||
passed := errorBP <= 1.0 // 1bp tolerance for regression tests
|
||||
|
||||
return &internal.IndividualTestResult{
|
||||
TestName: test.TestName,
|
||||
Passed: passed,
|
||||
ErrorBP: errorBP,
|
||||
}
|
||||
}
|
||||
|
||||
// Price calculation functions (simplified versions of auditor functions)
|
||||
func calculateUniswapV2PriceForRegression(converter *pkgmath.DecimalConverter, reserve0, reserve1 *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
if reserve0.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return nil, fmt.Errorf("reserve0 cannot be zero")
|
||||
}
|
||||
|
||||
// Normalize both to 18 decimals for calculation
|
||||
reserve0Normalized := new(big.Int).Set(reserve0.Value)
|
||||
reserve1Normalized := new(big.Int).Set(reserve1.Value)
|
||||
|
||||
// Scale to 18 decimals
|
||||
if reserve0.Decimals < 18 {
|
||||
scale0 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve0.Decimals)), nil)
|
||||
reserve0Normalized.Mul(reserve0Normalized, scale0)
|
||||
}
|
||||
if reserve1.Decimals < 18 {
|
||||
scale1 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve1.Decimals)), nil)
|
||||
reserve1Normalized.Mul(reserve1Normalized, scale1)
|
||||
}
|
||||
|
||||
// Calculate price = reserve1 / reserve0 in 18 decimal precision
|
||||
priceInt := new(big.Int).Mul(reserve1Normalized, new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceInt.Div(priceInt, reserve0Normalized)
|
||||
|
||||
return pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
}
|
||||
|
||||
func calculateUniswapV3PriceForRegression(converter *pkgmath.DecimalConverter, test *internal.PricingTest) (*pkgmath.UniversalDecimal, error) {
|
||||
if test.SqrtPriceX96 == "" {
|
||||
return nil, fmt.Errorf("sqrtPriceX96 is required for V3")
|
||||
}
|
||||
|
||||
sqrtPriceX96 := new(big.Int)
|
||||
_, success := sqrtPriceX96.SetString(test.SqrtPriceX96, 10)
|
||||
if !success {
|
||||
return nil, fmt.Errorf("invalid sqrtPriceX96 format")
|
||||
}
|
||||
|
||||
// Convert sqrtPriceX96 to price: price = (sqrtPriceX96 / 2^96)^2
|
||||
q96 := new(big.Int).Lsh(big.NewInt(1), 96) // 2^96
|
||||
|
||||
// Calculate raw price
|
||||
sqrtPriceFloat := new(big.Float).SetInt(sqrtPriceX96)
|
||||
q96Float := new(big.Float).SetInt(q96)
|
||||
sqrtPriceFloat.Quo(sqrtPriceFloat, q96Float)
|
||||
|
||||
// Square to get the price
|
||||
priceFloat := new(big.Float).Mul(sqrtPriceFloat, sqrtPriceFloat)
|
||||
|
||||
// Account for decimal differences (ETH/USDC: 18 vs 6 decimals)
|
||||
if test.TestName == "ETH_USDC_V3_Basic" {
|
||||
decimalAdjustment := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(12), nil))
|
||||
priceFloat.Mul(priceFloat, decimalAdjustment)
|
||||
}
|
||||
|
||||
// Convert to UniversalDecimal with 18 decimal precision
|
||||
scaleFactor := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceFloat.Mul(priceFloat, scaleFactor)
|
||||
priceInt, _ := priceFloat.Int(nil)
|
||||
|
||||
return pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
}
|
||||
|
||||
func calculateCurvePriceForRegression(converter *pkgmath.DecimalConverter, reserve0, reserve1 *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
// For stable swaps, price = reserve1 / reserve0 with decimal normalization
|
||||
if reserve0.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return nil, fmt.Errorf("reserve0 cannot be zero")
|
||||
}
|
||||
|
||||
reserve0Normalized := new(big.Int).Set(reserve0.Value)
|
||||
reserve1Normalized := new(big.Int).Set(reserve1.Value)
|
||||
|
||||
// Scale to 18 decimals
|
||||
if reserve0.Decimals < 18 {
|
||||
scale0 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve0.Decimals)), nil)
|
||||
reserve0Normalized.Mul(reserve0Normalized, scale0)
|
||||
}
|
||||
if reserve1.Decimals < 18 {
|
||||
scale1 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve1.Decimals)), nil)
|
||||
reserve1Normalized.Mul(reserve1Normalized, scale1)
|
||||
}
|
||||
|
||||
priceInt := new(big.Int).Mul(reserve1Normalized, new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceInt.Div(priceInt, reserve0Normalized)
|
||||
|
||||
return pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
}
|
||||
|
||||
func calculateBalancerPriceForRegression(converter *pkgmath.DecimalConverter, reserve0, reserve1 *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
// For 80/20 weighted pools: price = (reserve1 * weight0) / (reserve0 * weight1)
|
||||
// weight0 = 80%, weight1 = 20%
|
||||
if reserve0.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return nil, fmt.Errorf("reserve0 cannot be zero")
|
||||
}
|
||||
|
||||
reserve0Normalized := new(big.Int).Set(reserve0.Value)
|
||||
reserve1Normalized := new(big.Int).Set(reserve1.Value)
|
||||
|
||||
// Scale to 18 decimals
|
||||
if reserve0.Decimals < 18 {
|
||||
scale0 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve0.Decimals)), nil)
|
||||
reserve0Normalized.Mul(reserve0Normalized, scale0)
|
||||
}
|
||||
if reserve1.Decimals < 18 {
|
||||
scale1 := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(18-reserve1.Decimals)), nil)
|
||||
reserve1Normalized.Mul(reserve1Normalized, scale1)
|
||||
}
|
||||
|
||||
// Calculate weighted price using big.Float for precision
|
||||
reserve1Float := new(big.Float).SetInt(reserve1Normalized)
|
||||
reserve0Float := new(big.Float).SetInt(reserve0Normalized)
|
||||
weight0Float := big.NewFloat(80.0)
|
||||
weight1Float := big.NewFloat(20.0)
|
||||
|
||||
numerator := new(big.Float).Mul(reserve1Float, weight0Float)
|
||||
denominator := new(big.Float).Mul(reserve0Float, weight1Float)
|
||||
priceFloat := new(big.Float).Quo(numerator, denominator)
|
||||
|
||||
// Convert back to big.Int with 18 decimal precision
|
||||
scaleFactor := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceFloat.Mul(priceFloat, scaleFactor)
|
||||
priceInt, _ := priceFloat.Int(nil)
|
||||
|
||||
return pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
}
|
||||
|
||||
func calculateErrorBPForRegression(expected, actual *pkgmath.UniversalDecimal) float64 {
|
||||
if expected.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
if actual.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return 0.0
|
||||
}
|
||||
return 10000.0 // Max error if expected is 0 but actual is not
|
||||
}
|
||||
|
||||
// Calculate relative error: |actual - expected| / expected
|
||||
diff := new(big.Int).Sub(actual.Value, expected.Value)
|
||||
if diff.Sign() < 0 {
|
||||
diff.Neg(diff)
|
||||
}
|
||||
|
||||
// Convert to float for percentage calculation
|
||||
diffFloat, _ := new(big.Float).SetInt(diff).Float64()
|
||||
expectedFloat, _ := new(big.Float).SetInt(expected.Value).Float64()
|
||||
|
||||
if expectedFloat == 0 {
|
||||
return 10000.0
|
||||
}
|
||||
|
||||
return (diffFloat / expectedFloat) * 10000.0
|
||||
}
|
||||
|
||||
// TestArbitrageSpreadStability tests that arbitrage spread calculations remain stable
|
||||
func TestArbitrageSpreadStability(t *testing.T) {
|
||||
converter := pkgmath.NewDecimalConverter()
|
||||
|
||||
// Test that spread calculations don't introduce rounding errors
|
||||
testSpread := func(name string, price1Str, price2Str string, expectedSpreadBP, toleranceBP float64) {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
price1, _ := converter.FromString(price1Str, 18, "PRICE1")
|
||||
price2, _ := converter.FromString(price2Str, 18, "PRICE2")
|
||||
|
||||
// Calculate spread: |price2 - price1| / ((price1 + price2) / 2) * 10000
|
||||
diff := new(big.Int).Sub(price2.Value, price1.Value)
|
||||
if diff.Sign() < 0 {
|
||||
diff.Neg(diff)
|
||||
}
|
||||
|
||||
sum := new(big.Int).Add(price1.Value, price2.Value)
|
||||
avgPrice := new(big.Int).Div(sum, big.NewInt(2))
|
||||
|
||||
if avgPrice.Cmp(big.NewInt(0)) == 0 {
|
||||
t.Fatal("Average price cannot be zero")
|
||||
}
|
||||
|
||||
spreadFloat := new(big.Float).SetInt(diff)
|
||||
avgFloat := new(big.Float).SetInt(avgPrice)
|
||||
spreadFloat.Quo(spreadFloat, avgFloat)
|
||||
spreadFloat.Mul(spreadFloat, big.NewFloat(10000.0)) // Convert to basis points
|
||||
|
||||
actualSpreadBP, _ := spreadFloat.Float64()
|
||||
errorBP := absRegression(actualSpreadBP - expectedSpreadBP)
|
||||
|
||||
if errorBP > toleranceBP {
|
||||
t.Errorf("Spread error %.4f bp exceeds tolerance %.4f bp (expected %.4f bp, got %.4f bp)",
|
||||
errorBP, toleranceBP, expectedSpreadBP, actualSpreadBP)
|
||||
}
|
||||
|
||||
t.Logf("✓ %s: Spread=%.4f bp (expected %.4f bp, error=%.4f bp)",
|
||||
name, actualSpreadBP, expectedSpreadBP, errorBP)
|
||||
})
|
||||
}
|
||||
|
||||
// Test various spread scenarios
|
||||
testSpread("Small_Spread", "2000000000000000000000", "2001000000000000000000", 50.0, 1.0) // 0.05% spread
|
||||
testSpread("Medium_Spread", "2000000000000000000000", "2010000000000000000000", 498.8, 5.0) // ~0.5% spread
|
||||
testSpread("Large_Spread", "2000000000000000000000", "2100000000000000000000", 4878.0, 10.0) // ~4.9% spread
|
||||
testSpread("Minimal_Spread", "2000000000000000000000", "2000100000000000000000", 5.0, 0.1) // 0.005% spread
|
||||
}
|
||||
|
||||
func absRegression(x float64) float64 {
|
||||
if x < 0 {
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
||||
322
orig/tools/math-audit/regression_test.go
Normal file
322
orig/tools/math-audit/regression_test.go
Normal file
@@ -0,0 +1,322 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"testing"
|
||||
|
||||
pkgmath "github.com/fraktal/mev-beta/pkg/math"
|
||||
)
|
||||
|
||||
// ProfitThresholdTestCase defines a test case for profit threshold validation
|
||||
type ProfitThresholdTestCase struct {
|
||||
Name string
|
||||
Exchange string
|
||||
Reserve0 string
|
||||
Reserve1 string
|
||||
AmountIn string
|
||||
ExpectedProfitBP float64 // Expected profit in basis points
|
||||
ExpectedSpreadBP float64 // Expected spread in basis points
|
||||
MinProfitThresholdBP float64 // Minimum profit threshold in basis points
|
||||
Tolerance float64 // Error tolerance in basis points
|
||||
}
|
||||
|
||||
// TestProfitThresholdRegression ensures profit calculations remain stable
|
||||
func TestProfitThresholdRegression(t *testing.T) {
|
||||
// Initialize decimal converter
|
||||
converter := pkgmath.NewDecimalConverter()
|
||||
|
||||
testCases := []ProfitThresholdTestCase{
|
||||
{
|
||||
Name: "ETH_USDC_Small_Profit",
|
||||
Exchange: "uniswap_v2",
|
||||
Reserve0: "1000000000000000000000", // 1000 ETH
|
||||
Reserve1: "2000000000000", // 2M USDC (6 decimals)
|
||||
AmountIn: "1000000000000000000", // 1 ETH
|
||||
ExpectedProfitBP: 25.0, // 0.25% profit expected
|
||||
ExpectedSpreadBP: 50.0, // 0.5% spread expected
|
||||
MinProfitThresholdBP: 10.0, // 0.1% minimum profit
|
||||
Tolerance: 2.0, // 2bp tolerance
|
||||
},
|
||||
{
|
||||
Name: "WBTC_ETH_Medium_Profit",
|
||||
Exchange: "uniswap_v2",
|
||||
Reserve0: "50000000000", // 500 WBTC (8 decimals)
|
||||
Reserve1: "10000000000000000000000", // 10000 ETH
|
||||
AmountIn: "100000000", // 1 WBTC
|
||||
ExpectedProfitBP: 35.0, // 0.35% profit expected
|
||||
ExpectedSpreadBP: 70.0, // 0.7% spread expected
|
||||
MinProfitThresholdBP: 15.0, // 0.15% minimum profit
|
||||
Tolerance: 3.0, // 3bp tolerance
|
||||
},
|
||||
{
|
||||
Name: "ETH_USDC_V3_Concentrated",
|
||||
Exchange: "uniswap_v3",
|
||||
Reserve0: "1000000000000000000000", // 1000 ETH
|
||||
Reserve1: "2000000000000", // 2M USDC
|
||||
AmountIn: "500000000000000000", // 0.5 ETH
|
||||
ExpectedProfitBP: 15.0, // 0.15% profit expected
|
||||
ExpectedSpreadBP: 25.0, // 0.25% spread expected
|
||||
MinProfitThresholdBP: 5.0, // 0.05% minimum profit
|
||||
Tolerance: 1.5, // 1.5bp tolerance
|
||||
},
|
||||
{
|
||||
Name: "USDC_USDT_Stable_Spread",
|
||||
Exchange: "curve",
|
||||
Reserve0: "1000000000000", // 1M USDC (6 decimals)
|
||||
Reserve1: "1000000000000", // 1M USDT (6 decimals)
|
||||
AmountIn: "10000000000", // 10k USDC
|
||||
ExpectedProfitBP: 2.0, // 0.02% profit expected
|
||||
ExpectedSpreadBP: 5.0, // 0.05% spread expected
|
||||
MinProfitThresholdBP: 1.0, // 0.01% minimum profit
|
||||
Tolerance: 0.5, // 0.5bp tolerance
|
||||
},
|
||||
{
|
||||
Name: "ETH_USDC_80_20_Weighted",
|
||||
Exchange: "balancer",
|
||||
Reserve0: "800000000000000000000", // 800 ETH
|
||||
Reserve1: "400000000000", // 400k USDC
|
||||
AmountIn: "2000000000000000000", // 2 ETH
|
||||
ExpectedProfitBP: 40.0, // 0.4% profit expected
|
||||
ExpectedSpreadBP: 80.0, // 0.8% spread expected
|
||||
MinProfitThresholdBP: 20.0, // 0.2% minimum profit
|
||||
Tolerance: 5.0, // 5bp tolerance
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
// Calculate actual profit and spread
|
||||
actualProfitBP, actualSpreadBP, err := calculateProfitAndSpread(converter, tc)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to calculate profit and spread: %v", err)
|
||||
}
|
||||
|
||||
// Validate profit meets minimum threshold
|
||||
if actualProfitBP < tc.MinProfitThresholdBP {
|
||||
t.Errorf("Profit %.4f bp below minimum threshold %.4f bp",
|
||||
actualProfitBP, tc.MinProfitThresholdBP)
|
||||
}
|
||||
|
||||
// Validate profit within expected range
|
||||
profitError := abs(actualProfitBP - tc.ExpectedProfitBP)
|
||||
if profitError > tc.Tolerance {
|
||||
t.Errorf("Profit error %.4f bp exceeds tolerance %.4f bp (expected %.4f bp, got %.4f bp)",
|
||||
profitError, tc.Tolerance, tc.ExpectedProfitBP, actualProfitBP)
|
||||
}
|
||||
|
||||
// Validate spread within expected range
|
||||
spreadError := abs(actualSpreadBP - tc.ExpectedSpreadBP)
|
||||
if spreadError > tc.Tolerance*2 { // Allow 2x tolerance for spread
|
||||
t.Errorf("Spread error %.4f bp exceeds tolerance %.4f bp (expected %.4f bp, got %.4f bp)",
|
||||
spreadError, tc.Tolerance*2, tc.ExpectedSpreadBP, actualSpreadBP)
|
||||
}
|
||||
|
||||
t.Logf("✓ %s: Profit=%.4f bp, Spread=%.4f bp (within tolerance)",
|
||||
tc.Name, actualProfitBP, actualSpreadBP)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// calculateProfitAndSpread calculates profit and spread for a test case
|
||||
func calculateProfitAndSpread(converter *pkgmath.DecimalConverter, tc ProfitThresholdTestCase) (profitBP, spreadBP float64, err error) {
|
||||
// Determine decimals based on exchange and tokens
|
||||
reserve0Decimals, reserve1Decimals := getTokenDecimals(tc.Exchange, tc.Name)
|
||||
|
||||
// Convert amounts to UniversalDecimal
|
||||
reserve0, err := converter.FromString(tc.Reserve0, reserve0Decimals, "TOKEN0")
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("invalid reserve0: %w", err)
|
||||
}
|
||||
|
||||
reserve1, err := converter.FromString(tc.Reserve1, reserve1Decimals, "TOKEN1")
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("invalid reserve1: %w", err)
|
||||
}
|
||||
|
||||
amountIn, err := converter.FromString(tc.AmountIn, reserve0Decimals, "TOKEN0")
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("invalid amountIn: %w", err)
|
||||
}
|
||||
|
||||
// Calculate spot price
|
||||
var spotPrice *pkgmath.UniversalDecimal
|
||||
switch tc.Exchange {
|
||||
case "uniswap_v2":
|
||||
spotPrice, err = calculateUniswapV2Price(converter, reserve0, reserve1)
|
||||
case "uniswap_v3":
|
||||
spotPrice, err = calculateUniswapV3EstimatedPrice(converter, reserve0, reserve1)
|
||||
case "curve":
|
||||
spotPrice, err = calculateCurvePrice(converter, reserve0, reserve1)
|
||||
case "balancer":
|
||||
spotPrice, err = calculateBalancerPrice(converter, reserve0, reserve1)
|
||||
default:
|
||||
return 0, 0, fmt.Errorf("unsupported exchange: %s", tc.Exchange)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("failed to calculate spot price: %w", err)
|
||||
}
|
||||
|
||||
// Calculate amount out using AMM formula
|
||||
amountOut, err := calculateAMMAmountOut(converter, tc.Exchange, reserve0, reserve1, amountIn)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("failed to calculate amount out: %w", err)
|
||||
}
|
||||
|
||||
// Calculate execution price
|
||||
executionPrice := calculateExecutionPrice(converter, amountIn, amountOut, reserve0Decimals, reserve1Decimals)
|
||||
|
||||
// Calculate profit (difference from spot price)
|
||||
profitBP = calculateRelativeErrorBP(converter, spotPrice, executionPrice)
|
||||
|
||||
// Calculate spread (bid-ask spread approximation)
|
||||
spreadBP = profitBP * 2.0 // Simple approximation: spread = 2 * price impact
|
||||
|
||||
return profitBP, spreadBP, nil
|
||||
}
|
||||
|
||||
// Helper functions for price calculations
|
||||
func calculateUniswapV2Price(converter *pkgmath.DecimalConverter, reserve0, reserve1 *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
// Price = reserve1 / reserve0 (normalized to 18 decimals)
|
||||
priceInt := new(big.Int).Mul(reserve1.Value, new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceInt.Div(priceInt, reserve0.Value)
|
||||
return pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
}
|
||||
|
||||
func calculateUniswapV3EstimatedPrice(converter *pkgmath.DecimalConverter, reserve0, reserve1 *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
// For simplicity, use the same formula as V2 for testing
|
||||
return calculateUniswapV2Price(converter, reserve0, reserve1)
|
||||
}
|
||||
|
||||
func calculateCurvePrice(converter *pkgmath.DecimalConverter, reserve0, reserve1 *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
// For stable swaps, price is typically 1:1 with small variations
|
||||
return calculateUniswapV2Price(converter, reserve0, reserve1)
|
||||
}
|
||||
|
||||
func calculateBalancerPrice(converter *pkgmath.DecimalConverter, reserve0, reserve1 *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
// Weighted pool: price = (reserve1/weight1) / (reserve0/weight0)
|
||||
// Assuming 80/20 weights: weight0=0.8, weight1=0.2
|
||||
// price = (reserve1/0.2) / (reserve0/0.8) = (reserve1 * 0.8) / (reserve0 * 0.2) = (reserve1 * 4) / reserve0
|
||||
priceInt := new(big.Int).Mul(reserve1.Value, big.NewInt(4))
|
||||
priceInt.Mul(priceInt, new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceInt.Div(priceInt, reserve0.Value)
|
||||
return pkgmath.NewUniversalDecimal(priceInt, 18, "PRICE")
|
||||
}
|
||||
|
||||
func calculateAMMAmountOut(converter *pkgmath.DecimalConverter, exchange string, reserve0, reserve1, amountIn *pkgmath.UniversalDecimal) (*pkgmath.UniversalDecimal, error) {
|
||||
// Simplified AMM calculation: k = x * y, amountOut = y - k / (x + amountIn)
|
||||
// k = reserve0 * reserve1
|
||||
k := new(big.Int).Mul(reserve0.Value, reserve1.Value)
|
||||
|
||||
// newReserve0 = reserve0 + amountIn
|
||||
newReserve0 := new(big.Int).Add(reserve0.Value, amountIn.Value)
|
||||
|
||||
// newReserve1 = k / newReserve0
|
||||
newReserve1 := new(big.Int).Div(k, newReserve0)
|
||||
|
||||
// amountOut = reserve1 - newReserve1
|
||||
amountOut := new(big.Int).Sub(reserve1.Value, newReserve1)
|
||||
|
||||
// Apply 0.3% fee for most exchanges
|
||||
fee := new(big.Int).Div(amountOut, big.NewInt(333)) // ~0.3%
|
||||
amountOut.Sub(amountOut, fee)
|
||||
|
||||
return pkgmath.NewUniversalDecimal(amountOut, reserve1.Decimals, "TOKEN1")
|
||||
}
|
||||
|
||||
func calculateExecutionPrice(converter *pkgmath.DecimalConverter, amountIn, amountOut *pkgmath.UniversalDecimal, decimalsIn, decimalsOut uint8) *pkgmath.UniversalDecimal {
|
||||
// Execution price = amountOut / amountIn (normalized to 18 decimals)
|
||||
priceInt := new(big.Int).Mul(amountOut.Value, new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
|
||||
priceInt.Div(priceInt, amountIn.Value)
|
||||
|
||||
// Adjust for decimal differences
|
||||
if decimalsOut != decimalsIn {
|
||||
decimalDiff := int64(decimalsIn) - int64(decimalsOut)
|
||||
if decimalDiff > 0 {
|
||||
adjustment := new(big.Int).Exp(big.NewInt(10), big.NewInt(decimalDiff), nil)
|
||||
priceInt.Mul(priceInt, adjustment)
|
||||
} else {
|
||||
adjustment := new(big.Int).Exp(big.NewInt(10), big.NewInt(-decimalDiff), nil)
|
||||
priceInt.Div(priceInt, adjustment)
|
||||
}
|
||||
}
|
||||
|
||||
result, _ := pkgmath.NewUniversalDecimal(priceInt, 18, "EXECUTION_PRICE")
|
||||
return result
|
||||
}
|
||||
|
||||
func calculateRelativeErrorBP(converter *pkgmath.DecimalConverter, expected, actual *pkgmath.UniversalDecimal) float64 {
|
||||
if expected.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return 10000.0 // Max error if expected is zero
|
||||
}
|
||||
|
||||
// Calculate relative error: |actual - expected| / expected * 10000
|
||||
diff := new(big.Int).Sub(actual.Value, expected.Value)
|
||||
if diff.Sign() < 0 {
|
||||
diff.Neg(diff)
|
||||
}
|
||||
|
||||
// Convert to float64 for percentage calculation
|
||||
diffFloat, _ := new(big.Float).SetInt(diff).Float64()
|
||||
expectedFloat, _ := new(big.Float).SetInt(expected.Value).Float64()
|
||||
|
||||
if expectedFloat == 0 {
|
||||
return 10000.0
|
||||
}
|
||||
|
||||
return (diffFloat / expectedFloat) * 10000.0
|
||||
}
|
||||
|
||||
func getTokenDecimals(exchange, testName string) (uint8, uint8) {
|
||||
switch {
|
||||
case contains(testName, "ETH") && contains(testName, "USDC"):
|
||||
return 18, 6 // ETH=18, USDC=6
|
||||
case contains(testName, "WBTC") && contains(testName, "ETH"):
|
||||
return 8, 18 // WBTC=8, ETH=18
|
||||
case contains(testName, "USDC") && contains(testName, "USDT"):
|
||||
return 6, 6 // USDC=6, USDT=6
|
||||
default:
|
||||
return 18, 18 // Default to 18 decimals
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func abs(x float64) float64 {
|
||||
if x < 0 {
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
// BenchmarkProfitCalculation benchmarks profit calculation performance
|
||||
func BenchmarkProfitCalculation(b *testing.B) {
|
||||
converter := pkgmath.NewDecimalConverter()
|
||||
|
||||
tc := ProfitThresholdTestCase{
|
||||
Name: "ETH_USDC_Benchmark",
|
||||
Exchange: "uniswap_v2",
|
||||
Reserve0: "1000000000000000000000",
|
||||
Reserve1: "2000000000000",
|
||||
AmountIn: "1000000000000000000",
|
||||
ExpectedProfitBP: 25.0,
|
||||
ExpectedSpreadBP: 50.0,
|
||||
MinProfitThresholdBP: 10.0,
|
||||
Tolerance: 2.0,
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _, err := calculateProfitAndSpread(converter, tc)
|
||||
if err != nil {
|
||||
b.Fatalf("Benchmark failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
128
orig/tools/math-audit/reports/math/latest/audit_report.md
Normal file
128
orig/tools/math-audit/reports/math/latest/audit_report.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# MEV Bot Math Audit Report
|
||||
|
||||
**Generated:** 2025-10-09T07:54:04-05:00
|
||||
**Test Vectors:** default
|
||||
**Error Tolerance:** 1.0 basis points
|
||||
|
||||
## Executive Summary
|
||||
|
||||
**Overall Status:** ✅ PASS
|
||||
|
||||
### Summary Statistics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tests | 10 |
|
||||
| Passed Tests | 10 |
|
||||
| Failed Tests | 0 |
|
||||
| Success Rate | 100.00% |
|
||||
| Exchanges Tested | 4 |
|
||||
|
||||
## Exchange Results
|
||||
|
||||
### UNISWAP_V3
|
||||
|
||||
**Status:** ✅ PASS
|
||||
**Duration:** 0s
|
||||
|
||||
#### Test Statistics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tests | 2 |
|
||||
| Passed | 2 |
|
||||
| Failed | 0 |
|
||||
| Max Error | 0.0000 bp |
|
||||
| Avg Error | 0.0000 bp |
|
||||
|
||||
#### Test Breakdown
|
||||
|
||||
| Category | Tests |
|
||||
|----------|-------|
|
||||
| Pricing Functions | 0 |
|
||||
| Amount Calculations | 1 |
|
||||
| Price Impact | 0 |
|
||||
|
||||
### CURVE
|
||||
|
||||
**Status:** ✅ PASS
|
||||
**Duration:** 0s
|
||||
|
||||
#### Test Statistics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tests | 2 |
|
||||
| Passed | 2 |
|
||||
| Failed | 0 |
|
||||
| Max Error | 0.0000 bp |
|
||||
| Avg Error | 0.0000 bp |
|
||||
|
||||
#### Test Breakdown
|
||||
|
||||
| Category | Tests |
|
||||
|----------|-------|
|
||||
| Pricing Functions | 0 |
|
||||
| Amount Calculations | 1 |
|
||||
| Price Impact | 0 |
|
||||
|
||||
### BALANCER
|
||||
|
||||
**Status:** ✅ PASS
|
||||
**Duration:** 0s
|
||||
|
||||
#### Test Statistics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tests | 2 |
|
||||
| Passed | 2 |
|
||||
| Failed | 0 |
|
||||
| Max Error | 0.0000 bp |
|
||||
| Avg Error | 0.0000 bp |
|
||||
|
||||
#### Test Breakdown
|
||||
|
||||
| Category | Tests |
|
||||
|----------|-------|
|
||||
| Pricing Functions | 0 |
|
||||
| Amount Calculations | 1 |
|
||||
| Price Impact | 0 |
|
||||
|
||||
### UNISWAP_V2
|
||||
|
||||
**Status:** ✅ PASS
|
||||
**Duration:** 0s
|
||||
|
||||
#### Test Statistics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Total Tests | 4 |
|
||||
| Passed | 4 |
|
||||
| Failed | 0 |
|
||||
| Max Error | 0.0000 bp |
|
||||
| Avg Error | 0.0000 bp |
|
||||
|
||||
#### Test Breakdown
|
||||
|
||||
| Category | Tests |
|
||||
|----------|-------|
|
||||
| Pricing Functions | 0 |
|
||||
| Amount Calculations | 1 |
|
||||
| Price Impact | 1 |
|
||||
|
||||
## Recommendations
|
||||
|
||||
✅ All mathematical validations passed successfully.
|
||||
|
||||
### Next Steps
|
||||
|
||||
- Consider running extended test vectors for comprehensive validation
|
||||
- Implement continuous mathematical validation in CI/CD pipeline
|
||||
- Monitor for precision degradation with production data
|
||||
|
||||
---
|
||||
|
||||
*This report was generated by the MEV Bot Math Audit Tool*
|
||||
*Report generated at: 2025-10-09T07:54:04-05:00*
|
||||
129
orig/tools/math-audit/reports/math/latest/audit_results.json
Normal file
129
orig/tools/math-audit/reports/math/latest/audit_results.json
Normal file
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"timestamp": "2025-10-09T07:54:04.652531259-05:00",
|
||||
"vectors_file": "default",
|
||||
"tolerance_bp": 1,
|
||||
"exchange_results": {
|
||||
"balancer": {
|
||||
"exchange_type": "balancer",
|
||||
"total_tests": 2,
|
||||
"passed_tests": 2,
|
||||
"failed_tests": 0,
|
||||
"max_error_bp": 0,
|
||||
"avg_error_bp": 0,
|
||||
"failed_cases": [],
|
||||
"test_results": [
|
||||
{
|
||||
"test_name": "Weighted_80_20_Pool",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 23129,
|
||||
"description": "Price calculation test for balancer"
|
||||
},
|
||||
{
|
||||
"test_name": "Weighted_Pool_Swap",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 43,
|
||||
"description": "Amount calculation test for balancer"
|
||||
}
|
||||
],
|
||||
"duration": 25108
|
||||
},
|
||||
"curve": {
|
||||
"exchange_type": "curve",
|
||||
"total_tests": 2,
|
||||
"passed_tests": 2,
|
||||
"failed_tests": 0,
|
||||
"max_error_bp": 0,
|
||||
"avg_error_bp": 0,
|
||||
"failed_cases": [],
|
||||
"test_results": [
|
||||
{
|
||||
"test_name": "Stable_USDC_USDT",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 11825,
|
||||
"description": "Price calculation test for curve"
|
||||
},
|
||||
{
|
||||
"test_name": "Stable_Swap_Low_Impact",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 44,
|
||||
"description": "Amount calculation test for curve"
|
||||
}
|
||||
],
|
||||
"duration": 13510
|
||||
},
|
||||
"uniswap_v2": {
|
||||
"exchange_type": "uniswap_v2",
|
||||
"total_tests": 4,
|
||||
"passed_tests": 4,
|
||||
"failed_tests": 0,
|
||||
"max_error_bp": 0,
|
||||
"avg_error_bp": 0,
|
||||
"failed_cases": [],
|
||||
"test_results": [
|
||||
{
|
||||
"test_name": "ETH_USDC_Basic",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 13525,
|
||||
"description": "Price calculation test for uniswap_v2"
|
||||
},
|
||||
{
|
||||
"test_name": "WBTC_ETH_Basic",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 9079,
|
||||
"description": "Price calculation test for uniswap_v2"
|
||||
},
|
||||
{
|
||||
"test_name": "ETH_to_USDC_Swap",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 56,
|
||||
"description": "Amount calculation test for uniswap_v2"
|
||||
},
|
||||
{
|
||||
"test_name": "Large_ETH_Swap_Impact",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 69,
|
||||
"description": "Price impact test for uniswap_v2"
|
||||
}
|
||||
],
|
||||
"duration": 26862
|
||||
},
|
||||
"uniswap_v3": {
|
||||
"exchange_type": "uniswap_v3",
|
||||
"total_tests": 2,
|
||||
"passed_tests": 2,
|
||||
"failed_tests": 0,
|
||||
"max_error_bp": 6.8468e-13,
|
||||
"avg_error_bp": 3.4234e-13,
|
||||
"failed_cases": [],
|
||||
"test_results": [
|
||||
{
|
||||
"test_name": "ETH_USDC_V3_Basic",
|
||||
"passed": true,
|
||||
"error_bp": 6.8468e-13,
|
||||
"duration": 16251,
|
||||
"description": "Price calculation test for uniswap_v3"
|
||||
},
|
||||
{
|
||||
"test_name": "V3_Concentrated_Liquidity",
|
||||
"passed": true,
|
||||
"error_bp": 0,
|
||||
"duration": 75,
|
||||
"description": "Amount calculation test for uniswap_v3"
|
||||
}
|
||||
],
|
||||
"duration": 18398
|
||||
}
|
||||
},
|
||||
"overall_passed": true,
|
||||
"total_tests": 10,
|
||||
"total_passed": 10,
|
||||
"total_failed": 0
|
||||
}
|
||||
25
orig/tools/math-audit/vectors/balancer_wbtc_usdc.json
Normal file
25
orig/tools/math-audit/vectors/balancer_wbtc_usdc.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "balancer_wbtc_usdc",
|
||||
"description": "Simplified Balancer 50/50 weighted pool",
|
||||
"pool": {
|
||||
"address": "0x0000000000000000000000000000000000000007",
|
||||
"exchange": "balancer",
|
||||
"token0": { "symbol": "WBTC", "decimals": 18 },
|
||||
"token1": { "symbol": "USDC", "decimals": 18 },
|
||||
"reserve0": { "value": "100000000000000000000", "decimals": 18, "symbol": "WBTC" },
|
||||
"reserve1": { "value": "100000000000000000000", "decimals": 18, "symbol": "USDC" },
|
||||
"weights": [
|
||||
{ "value": "5", "decimals": 1, "symbol": "W0" },
|
||||
{ "value": "5", "decimals": 1, "symbol": "W1" }
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"name": "amount_out_0_001_wbtc",
|
||||
"type": "amount_out",
|
||||
"amount_in": { "value": "1000000000000000000", "decimals": 18, "symbol": "WBTC" },
|
||||
"expected": { "value": "1000000000000000000", "decimals": 18, "symbol": "USDC" },
|
||||
"tolerance_bps": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
23
orig/tools/math-audit/vectors/camelot_algebra_weth_usdc.json
Normal file
23
orig/tools/math-audit/vectors/camelot_algebra_weth_usdc.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "camelot_algebra_weth_usdc",
|
||||
"description": "Camelot/Algebra concentrated liquidity sample",
|
||||
"pool": {
|
||||
"address": "0x0000000000000000000000000000000000000004",
|
||||
"exchange": "camelot",
|
||||
"token0": { "symbol": "WETH", "decimals": 18 },
|
||||
"token1": { "symbol": "USDC", "decimals": 18 },
|
||||
"reserve0": { "value": "400000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"reserve1": { "value": "900000000000000000000", "decimals": 18, "symbol": "USDC" },
|
||||
"fee": { "value": "500", "decimals": 6, "symbol": "FEE" },
|
||||
"liquidity": "1"
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"name": "amount_out_0_1_weth",
|
||||
"type": "amount_out",
|
||||
"amount_in": { "value": "100000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"expected": { "value": "224831320273846572", "decimals": 18, "symbol": "USDC" },
|
||||
"tolerance_bps": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
23
orig/tools/math-audit/vectors/curve_usdc_usdt.json
Normal file
23
orig/tools/math-audit/vectors/curve_usdc_usdt.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "curve_usdc_usdt",
|
||||
"description": "Curve stable swap example with 0.04% fee",
|
||||
"pool": {
|
||||
"address": "0x0000000000000000000000000000000000000006",
|
||||
"exchange": "curve",
|
||||
"token0": { "symbol": "USDC", "decimals": 6 },
|
||||
"token1": { "symbol": "USDT", "decimals": 6 },
|
||||
"reserve0": { "value": "1000000000000", "decimals": 6, "symbol": "USDC" },
|
||||
"reserve1": { "value": "1000000000000", "decimals": 6, "symbol": "USDT" },
|
||||
"fee": { "value": "4", "decimals": 4, "symbol": "FEE" },
|
||||
"amplification": "100"
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"name": "amount_out_1_usdc",
|
||||
"type": "amount_out",
|
||||
"amount_in": { "value": "1000000", "decimals": 6, "symbol": "USDC" },
|
||||
"expected": { "value": "999600", "decimals": 6, "symbol": "USDT" },
|
||||
"tolerance_bps": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
207
orig/tools/math-audit/vectors/default.json
Normal file
207
orig/tools/math-audit/vectors/default.json
Normal file
@@ -0,0 +1,207 @@
|
||||
{
|
||||
"name": "default",
|
||||
"version": "1.0.0",
|
||||
"timestamp": "2024-10-08T00:00:00Z",
|
||||
"description": "Default test vectors for MEV Bot math validation",
|
||||
"exchanges": {
|
||||
"uniswap_v2": {
|
||||
"exchange_type": "uniswap_v2",
|
||||
"pricing_tests": [
|
||||
{
|
||||
"test_name": "ETH_USDC_Standard_Pool",
|
||||
"description": "Standard ETH/USDC pool price calculation",
|
||||
"reserve_0": "1000000000000000000000",
|
||||
"reserve_1": "2000000000000",
|
||||
"expected_price": "2000000000000000000000",
|
||||
"tolerance": 1.0
|
||||
},
|
||||
{
|
||||
"test_name": "WBTC_ETH_High_Value",
|
||||
"description": "High value WBTC/ETH pool",
|
||||
"reserve_0": "50000000000",
|
||||
"reserve_1": "10000000000000000000000",
|
||||
"expected_price": "20000000000000000000",
|
||||
"tolerance": 1.0
|
||||
},
|
||||
{
|
||||
"test_name": "Small_Pool_Precision",
|
||||
"description": "Small liquidity pool precision test",
|
||||
"reserve_0": "1000000000000000000",
|
||||
"reserve_1": "2000000000",
|
||||
"expected_price": "2000000000000000000000",
|
||||
"tolerance": 5.0
|
||||
}
|
||||
],
|
||||
"amount_tests": [
|
||||
{
|
||||
"test_name": "ETH_to_USDC_Small_Swap",
|
||||
"description": "Small ETH to USDC swap",
|
||||
"reserve_0": "1000000000000000000000",
|
||||
"reserve_1": "2000000000000",
|
||||
"amount_in": "1000000000000000000",
|
||||
"token_in": "0",
|
||||
"fee": "3000",
|
||||
"expected_amount_out": "1994006985000",
|
||||
"tolerance": 5.0
|
||||
},
|
||||
{
|
||||
"test_name": "USDC_to_ETH_Large_Swap",
|
||||
"description": "Large USDC to ETH swap",
|
||||
"reserve_0": "1000000000000000000000",
|
||||
"reserve_1": "2000000000000",
|
||||
"amount_in": "10000000000",
|
||||
"token_in": "1",
|
||||
"fee": "3000",
|
||||
"expected_amount_out": "4975124378109453",
|
||||
"tolerance": 10.0
|
||||
}
|
||||
],
|
||||
"price_impact_tests": [
|
||||
{
|
||||
"test_name": "Large_ETH_Swap_Impact",
|
||||
"description": "Price impact of large ETH swap",
|
||||
"reserve_0": "1000000000000000000000",
|
||||
"reserve_1": "2000000000000",
|
||||
"swap_amount": "100000000000000000000",
|
||||
"token_in": "0",
|
||||
"expected_price_impact": "9.09",
|
||||
"tolerance": 10.0
|
||||
}
|
||||
]
|
||||
},
|
||||
"uniswap_v3": {
|
||||
"exchange_type": "uniswap_v3",
|
||||
"pricing_tests": [
|
||||
{
|
||||
"test_name": "ETH_USDC_V3_Basic",
|
||||
"description": "ETH/USDC V3 price from sqrtPriceX96",
|
||||
"sqrt_price_x96": "3543191142285914327220224",
|
||||
"expected_price": "2000000000000000000000",
|
||||
"tolerance": 1.0
|
||||
},
|
||||
{
|
||||
"test_name": "WBTC_ETH_V3_Tick",
|
||||
"description": "WBTC/ETH V3 price from tick",
|
||||
"tick": 92233,
|
||||
"expected_price": "20000000000000000000",
|
||||
"tolerance": 2.0
|
||||
}
|
||||
],
|
||||
"amount_tests": [
|
||||
{
|
||||
"test_name": "V3_Concentrated_Liquidity_Swap",
|
||||
"description": "Swap within concentrated liquidity range",
|
||||
"reserve_0": "1000000000000000000000",
|
||||
"reserve_1": "2000000000000",
|
||||
"amount_in": "1000000000000000000",
|
||||
"token_in": "0",
|
||||
"fee": "500",
|
||||
"expected_amount_out": "1999000000000",
|
||||
"tolerance": 2.0
|
||||
}
|
||||
],
|
||||
"price_impact_tests": [
|
||||
{
|
||||
"test_name": "V3_Cross_Tick_Impact",
|
||||
"description": "Price impact crossing multiple ticks",
|
||||
"reserve_0": "1000000000000000000000",
|
||||
"reserve_1": "2000000000000",
|
||||
"swap_amount": "50000000000000000000",
|
||||
"token_in": "0",
|
||||
"expected_price_impact": "4.76",
|
||||
"tolerance": 20.0
|
||||
}
|
||||
]
|
||||
},
|
||||
"curve": {
|
||||
"exchange_type": "curve",
|
||||
"pricing_tests": [
|
||||
{
|
||||
"test_name": "Stable_USDC_USDT_Pool",
|
||||
"description": "Stable swap USDC/USDT pricing",
|
||||
"reserve_0": "1000000000000",
|
||||
"reserve_1": "1000000000000",
|
||||
"expected_price": "1000000000000000000",
|
||||
"tolerance": 0.5
|
||||
},
|
||||
{
|
||||
"test_name": "Imbalanced_Stable_Pool",
|
||||
"description": "Imbalanced stable pool pricing",
|
||||
"reserve_0": "2000000000000",
|
||||
"reserve_1": "1000000000000",
|
||||
"expected_price": "980000000000000000",
|
||||
"tolerance": 5.0
|
||||
}
|
||||
],
|
||||
"amount_tests": [
|
||||
{
|
||||
"test_name": "Stable_Swap_Low_Impact",
|
||||
"description": "Low price impact stable swap",
|
||||
"reserve_0": "1000000000000",
|
||||
"reserve_1": "1000000000000",
|
||||
"amount_in": "1000000000",
|
||||
"token_in": "0",
|
||||
"expected_amount_out": "999000000",
|
||||
"tolerance": 1.0
|
||||
}
|
||||
],
|
||||
"price_impact_tests": [
|
||||
{
|
||||
"test_name": "Large_Stable_Swap_Impact",
|
||||
"description": "Large swap in stable pool",
|
||||
"reserve_0": "1000000000000",
|
||||
"reserve_1": "1000000000000",
|
||||
"swap_amount": "100000000000",
|
||||
"token_in": "0",
|
||||
"expected_price_impact": "0.5",
|
||||
"tolerance": 2.0
|
||||
}
|
||||
]
|
||||
},
|
||||
"balancer": {
|
||||
"exchange_type": "balancer",
|
||||
"pricing_tests": [
|
||||
{
|
||||
"test_name": "Weighted_80_20_ETH_USDC",
|
||||
"description": "80/20 weighted pool ETH/USDC",
|
||||
"reserve_0": "800000000000000000000",
|
||||
"reserve_1": "400000000000",
|
||||
"expected_price": "2500000000000000000000",
|
||||
"tolerance": 2.0
|
||||
},
|
||||
{
|
||||
"test_name": "Weighted_50_50_Pool",
|
||||
"description": "50/50 weighted pool",
|
||||
"reserve_0": "1000000000000000000000",
|
||||
"reserve_1": "2000000000000",
|
||||
"expected_price": "2000000000000000000000",
|
||||
"tolerance": 1.0
|
||||
}
|
||||
],
|
||||
"amount_tests": [
|
||||
{
|
||||
"test_name": "Weighted_Pool_Small_Swap",
|
||||
"description": "Small swap in weighted pool",
|
||||
"reserve_0": "800000000000000000000",
|
||||
"reserve_1": "400000000000",
|
||||
"amount_in": "1000000000000000000",
|
||||
"token_in": "0",
|
||||
"expected_amount_out": "2475000000000",
|
||||
"tolerance": 5.0
|
||||
}
|
||||
],
|
||||
"price_impact_tests": [
|
||||
{
|
||||
"test_name": "Weighted_Pool_Price_Impact",
|
||||
"description": "Price impact in weighted pool",
|
||||
"reserve_0": "800000000000000000000",
|
||||
"reserve_1": "400000000000",
|
||||
"swap_amount": "80000000000000000000",
|
||||
"token_in": "0",
|
||||
"expected_price_impact": "12.5",
|
||||
"tolerance": 15.0
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
21
orig/tools/math-audit/vectors/default_formatted.json
Normal file
21
orig/tools/math-audit/vectors/default_formatted.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "default_formatted",
|
||||
"description": "Default formatted test vectors for MEV Bot math validation",
|
||||
"pool": {
|
||||
"address": "0x0000000000000000000000000000000000000001",
|
||||
"exchange": "uniswap_v2",
|
||||
"token0": { "symbol": "WETH", "decimals": 18 },
|
||||
"token1": { "symbol": "USDC", "decimals": 18 },
|
||||
"reserve0": { "value": "1000000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"reserve1": { "value": "2000000000000", "decimals": 18, "symbol": "USDC" }
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"name": "default_amount_out_test",
|
||||
"type": "amount_out",
|
||||
"amount_in": { "value": "1000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"expected": { "value": "1994006985000", "decimals": 18, "symbol": "USDC" },
|
||||
"tolerance_bps": 500
|
||||
}
|
||||
]
|
||||
}
|
||||
24
orig/tools/math-audit/vectors/ramses_v3_weth_usdc.json
Normal file
24
orig/tools/math-audit/vectors/ramses_v3_weth_usdc.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "ramses_v3_weth_usdc",
|
||||
"description": "Ramses V3 concentrated liquidity example",
|
||||
"pool": {
|
||||
"address": "0x0000000000000000000000000000000000000005",
|
||||
"exchange": "ramses",
|
||||
"token0": { "symbol": "WETH", "decimals": 18 },
|
||||
"token1": { "symbol": "USDC", "decimals": 18 },
|
||||
"reserve0": { "value": "200000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"reserve1": { "value": "400000000000000000000", "decimals": 18, "symbol": "USDC" },
|
||||
"fee": { "value": "3000", "decimals": 6, "symbol": "FEE" },
|
||||
"sqrt_price_x96": "79228162514264337593543950336",
|
||||
"liquidity": "1"
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"name": "amount_out_0_05_weth",
|
||||
"type": "amount_out",
|
||||
"amount_in": { "value": "50000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"expected": { "value": "99675155967375131", "decimals": 18, "symbol": "USDC" },
|
||||
"tolerance_bps": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
21
orig/tools/math-audit/vectors/traderjoe_usdc_weth.json
Normal file
21
orig/tools/math-audit/vectors/traderjoe_usdc_weth.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "traderjoe_usdc_weth",
|
||||
"description": "TraderJoe constant-product pool example mirroring Uniswap V2 math",
|
||||
"pool": {
|
||||
"address": "0x0000000000000000000000000000000000000002",
|
||||
"exchange": "traderjoe",
|
||||
"token0": { "symbol": "WETH", "decimals": 18 },
|
||||
"token1": { "symbol": "USDC", "decimals": 18 },
|
||||
"reserve0": { "value": "800000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"reserve1": { "value": "1200000000000000000000000", "decimals": 18, "symbol": "USDC" }
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"name": "amount_out_3_weth",
|
||||
"type": "amount_out",
|
||||
"amount_in": { "value": "3000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"expected": { "value": "4469788577954173832583", "decimals": 18, "symbol": "USDC" },
|
||||
"tolerance_bps": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
21
orig/tools/math-audit/vectors/uniswap_v2_usdc_weth.json
Normal file
21
orig/tools/math-audit/vectors/uniswap_v2_usdc_weth.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "uniswap_v2_usdc_weth",
|
||||
"description": "Uniswap V2 style pool with 10k WETH against 20M USDC",
|
||||
"pool": {
|
||||
"address": "0x0000000000000000000000000000000000000001",
|
||||
"exchange": "uniswap_v2",
|
||||
"token0": { "symbol": "WETH", "decimals": 18 },
|
||||
"token1": { "symbol": "USDC", "decimals": 18 },
|
||||
"reserve0": { "value": "500000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"reserve1": { "value": "1000000000000000000000000", "decimals": 18, "symbol": "USDC" }
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"name": "amount_out_5_weth",
|
||||
"type": "amount_out",
|
||||
"amount_in": { "value": "5000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"expected": { "value": "9871580343970612988504", "decimals": 18, "symbol": "USDC" },
|
||||
"tolerance_bps": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
24
orig/tools/math-audit/vectors/uniswap_v3_weth_usdc.json
Normal file
24
orig/tools/math-audit/vectors/uniswap_v3_weth_usdc.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "uniswap_v3_weth_usdc",
|
||||
"description": "Uniswap V3 style pool around price 1:1 for deterministic regression",
|
||||
"pool": {
|
||||
"address": "0x0000000000000000000000000000000000000003",
|
||||
"exchange": "uniswap_v3",
|
||||
"token0": { "symbol": "WETH", "decimals": 18 },
|
||||
"token1": { "symbol": "USDC", "decimals": 18 },
|
||||
"reserve0": { "value": "500000000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"reserve1": { "value": "1000000000000000000000", "decimals": 18, "symbol": "USDC" },
|
||||
"fee": { "value": "3000", "decimals": 6, "symbol": "FEE" },
|
||||
"sqrt_price_x96": "79228162514264337593543950336",
|
||||
"liquidity": "1"
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"name": "amount_out_0_1_weth",
|
||||
"type": "amount_out",
|
||||
"amount_in": { "value": "100000000000000000", "decimals": 18, "symbol": "WETH" },
|
||||
"expected": { "value": "199360247566635212", "decimals": 18, "symbol": "USDC" },
|
||||
"tolerance_bps": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
31
orig/tools/opportunity-validator/go.mod
Normal file
31
orig/tools/opportunity-validator/go.mod
Normal file
@@ -0,0 +1,31 @@
|
||||
module github.com/fraktal/mev-beta/tools/opportunity-validator
|
||||
|
||||
go 1.25.0
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../../
|
||||
|
||||
require github.com/fraktal/mev-beta v0.0.0-00010101000000-000000000000
|
||||
|
||||
require (
|
||||
github.com/bits-and-blooms/bitset v1.24.0 // indirect
|
||||
github.com/consensys/gnark-crypto v0.19.0 // indirect
|
||||
github.com/crate-crypto/go-eth-kzg v1.4.0 // indirect
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect
|
||||
github.com/deckarep/golang-set/v2 v2.6.0 // indirect
|
||||
github.com/ethereum/go-ethereum v1.16.3 // indirect
|
||||
github.com/ethereum/go-verkle v0.2.2 // indirect
|
||||
github.com/fsnotify/fsnotify v1.6.0 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/holiman/uint256 v1.3.2 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.32 // indirect
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
golang.org/x/crypto v0.42.0 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
golang.org/x/time v0.10.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
46
orig/tools/opportunity-validator/go.sum
Normal file
46
orig/tools/opportunity-validator/go.sum
Normal file
@@ -0,0 +1,46 @@
|
||||
github.com/bits-and-blooms/bitset v1.24.0 h1:H4x4TuulnokZKvHLfzVRTHJfFfnHEeSYJizujEZvmAM=
|
||||
github.com/bits-and-blooms/bitset v1.24.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/consensys/gnark-crypto v0.19.0 h1:zXCqeY2txSaMl6G5wFpZzMWJU9HPNh8qxPnYJ1BL9vA=
|
||||
github.com/consensys/gnark-crypto v0.19.0/go.mod h1:rT23F0XSZqE0mUA0+pRtnL56IbPxs6gp4CeRsBk4XS0=
|
||||
github.com/crate-crypto/go-eth-kzg v1.4.0 h1:WzDGjHk4gFg6YzV0rJOAsTK4z3Qkz5jd4RE3DAvPFkg=
|
||||
github.com/crate-crypto/go-eth-kzg v1.4.0/go.mod h1:J9/u5sWfznSObptgfa92Jq8rTswn6ahQWEuiLHOjCUI=
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a h1:W8mUrRp6NOVl3J+MYp5kPMoUZPp7aOYHtaua31lwRHg=
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a/go.mod h1:sTwzHBvIzm2RfVCGNEBZgRyjwK40bVoun3ZnGOCafNM=
|
||||
github.com/deckarep/golang-set/v2 v2.6.0 h1:XfcQbWM1LlMB8BsJ8N9vW5ehnnPVIw0je80NsVHagjM=
|
||||
github.com/deckarep/golang-set/v2 v2.6.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4=
|
||||
github.com/ethereum/go-ethereum v1.16.3 h1:nDoBSrmsrPbrDIVLTkDQCy1U9KdHN+F2PzvMbDoS42Q=
|
||||
github.com/ethereum/go-ethereum v1.16.3/go.mod h1:Lrsc6bt9Gm9RyvhfFK53vboCia8kpF9nv+2Ukntnl+8=
|
||||
github.com/ethereum/go-verkle v0.2.2 h1:I2W0WjnrFUIzzVPwm8ykY+7pL2d4VhlsePn4j7cnFk8=
|
||||
github.com/ethereum/go-verkle v0.2.2/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk=
|
||||
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
|
||||
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA=
|
||||
github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
||||
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible h1:Bn1aCHHRnjv4Bl16T8rcaFjYSrGrIZvpiGO6P3Q4GpU=
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
|
||||
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
|
||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
|
||||
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,602 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/pkg/arbitrage"
|
||||
"github.com/fraktal/mev-beta/pkg/math"
|
||||
)
|
||||
|
||||
type ValidatorConfig struct {
|
||||
Exchanges string
|
||||
MinProfitBP float64
|
||||
MaxSlippage float64
|
||||
OutputDir string
|
||||
Verbose bool
|
||||
DryRun bool
|
||||
TestMode bool
|
||||
}
|
||||
|
||||
type OpportunityValidator struct {
|
||||
config *ValidatorConfig
|
||||
supportedExchanges []string
|
||||
detectionEngine *arbitrage.DetectionEngine
|
||||
calculator *math.ArbitrageCalculator
|
||||
results *ValidationResults
|
||||
}
|
||||
|
||||
type ValidationResults struct {
|
||||
TotalOpportunities int `json:"total_opportunities"`
|
||||
ValidOpportunities int `json:"valid_opportunities"`
|
||||
InvalidOpportunities int `json:"invalid_opportunities"`
|
||||
AverageProfitBP float64 `json:"average_profit_bp"`
|
||||
MaxProfitBP float64 `json:"max_profit_bp"`
|
||||
OpportunityDetails []OpportunityResult `json:"opportunity_details"`
|
||||
ExchangeBreakdown map[string]int `json:"exchange_breakdown"`
|
||||
ValidationErrors []ValidationError `json:"validation_errors"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
DurationMs int64 `json:"duration_ms"`
|
||||
}
|
||||
|
||||
type OpportunityResult struct {
|
||||
ID string `json:"id"`
|
||||
Exchange1 string `json:"exchange1"`
|
||||
Exchange2 string `json:"exchange2"`
|
||||
TokenA string `json:"token_a"`
|
||||
TokenB string `json:"token_b"`
|
||||
ProfitBP float64 `json:"profit_bp"`
|
||||
SlippageBP float64 `json:"slippage_bp"`
|
||||
GasCostETH float64 `json:"gas_cost_eth"`
|
||||
NetProfitBP float64 `json:"net_profit_bp"`
|
||||
ExecutionTime time.Time `json:"execution_time"`
|
||||
Valid bool `json:"valid"`
|
||||
ValidationNotes []string `json:"validation_notes"`
|
||||
}
|
||||
|
||||
type ValidationError struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
Exchange string `json:"exchange,omitempty"`
|
||||
TokenPair string `json:"token_pair,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
func NewOpportunityValidator(config *ValidatorConfig) (*OpportunityValidator, error) {
|
||||
// Parse supported exchanges
|
||||
exchanges := strings.Split(config.Exchanges, ",")
|
||||
for i, exchange := range exchanges {
|
||||
exchanges[i] = strings.TrimSpace(exchange)
|
||||
}
|
||||
|
||||
// Initialize detection engine
|
||||
detectionEngine, err := arbitrage.NewDetectionEngine(&arbitrage.DetectionEngineConfig{
|
||||
MinProfitBasisPoints: config.MinProfitBP,
|
||||
MaxSlippageBasisPoints: config.MaxSlippage,
|
||||
EnabledExchanges: exchanges,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to initialize detection engine: %w", err)
|
||||
}
|
||||
|
||||
// Initialize arbitrage calculator
|
||||
calculator := math.NewArbitrageCalculator()
|
||||
|
||||
return &OpportunityValidator{
|
||||
config: config,
|
||||
supportedExchanges: exchanges,
|
||||
detectionEngine: detectionEngine,
|
||||
calculator: calculator,
|
||||
results: &ValidationResults{
|
||||
OpportunityDetails: make([]OpportunityResult, 0),
|
||||
ExchangeBreakdown: make(map[string]int),
|
||||
ValidationErrors: make([]ValidationError, 0),
|
||||
Timestamp: time.Now(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) ValidateOpportunities(ctx context.Context) error {
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
ov.results.DurationMs = time.Since(startTime).Milliseconds()
|
||||
}()
|
||||
|
||||
if ov.config.TestMode {
|
||||
return ov.validateTestOpportunities(ctx)
|
||||
}
|
||||
|
||||
return ov.validateRealOpportunities(ctx)
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) validateTestOpportunities(ctx context.Context) error {
|
||||
// Create simulated test opportunities
|
||||
testOpportunities := ov.generateTestOpportunities()
|
||||
|
||||
for _, opportunity := range testOpportunities {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
result := ov.validateSingleOpportunity(opportunity)
|
||||
ov.results.OpportunityDetails = append(ov.results.OpportunityDetails, result)
|
||||
ov.updateStatistics(result)
|
||||
|
||||
if ov.config.Verbose {
|
||||
fmt.Printf("Validated opportunity %s: Valid=%t, Profit=%.2f bp\n",
|
||||
result.ID, result.Valid, result.ProfitBP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) validateRealOpportunities(ctx context.Context) error {
|
||||
// In real mode, we would connect to live data sources
|
||||
// For now, implement basic validation framework
|
||||
|
||||
if ov.config.Verbose {
|
||||
fmt.Println("Scanning for real-time arbitrage opportunities...")
|
||||
}
|
||||
|
||||
// This would integrate with the actual market scanner
|
||||
// For demonstration, create a few real-world scenarios
|
||||
realOpportunities := ov.generateRealWorldScenarios()
|
||||
|
||||
for _, opportunity := range realOpportunities {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
result := ov.validateSingleOpportunity(opportunity)
|
||||
ov.results.OpportunityDetails = append(ov.results.OpportunityDetails, result)
|
||||
ov.updateStatistics(result)
|
||||
|
||||
if ov.config.Verbose {
|
||||
fmt.Printf("Validated real opportunity %s: Valid=%t, Profit=%.2f bp\n",
|
||||
result.ID, result.Valid, result.ProfitBP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) validateSingleOpportunity(opportunity *TestOpportunity) OpportunityResult {
|
||||
result := OpportunityResult{
|
||||
ID: opportunity.ID,
|
||||
Exchange1: opportunity.Exchange1,
|
||||
Exchange2: opportunity.Exchange2,
|
||||
TokenA: opportunity.TokenA,
|
||||
TokenB: opportunity.TokenB,
|
||||
ExecutionTime: time.Now(),
|
||||
ValidationNotes: make([]string, 0),
|
||||
}
|
||||
|
||||
// Calculate profit using arbitrage calculator
|
||||
profitCalculation, err := ov.calculateProfit(opportunity)
|
||||
if err != nil {
|
||||
ov.addValidationError("profit_calculation", err.Error(), opportunity.Exchange1,
|
||||
fmt.Sprintf("%s/%s", opportunity.TokenA, opportunity.TokenB))
|
||||
result.Valid = false
|
||||
result.ValidationNotes = append(result.ValidationNotes, fmt.Sprintf("Profit calculation failed: %v", err))
|
||||
return result
|
||||
}
|
||||
|
||||
result.ProfitBP = profitCalculation.ProfitBP
|
||||
result.SlippageBP = profitCalculation.SlippageBP
|
||||
result.GasCostETH = profitCalculation.GasCostETH
|
||||
result.NetProfitBP = profitCalculation.NetProfitBP
|
||||
|
||||
// Validate profit threshold
|
||||
if result.ProfitBP < ov.config.MinProfitBP {
|
||||
result.Valid = false
|
||||
result.ValidationNotes = append(result.ValidationNotes,
|
||||
fmt.Sprintf("Profit %.2f bp below minimum threshold %.2f bp", result.ProfitBP, ov.config.MinProfitBP))
|
||||
}
|
||||
|
||||
// Validate slippage threshold
|
||||
if result.SlippageBP > ov.config.MaxSlippage {
|
||||
result.Valid = false
|
||||
result.ValidationNotes = append(result.ValidationNotes,
|
||||
fmt.Sprintf("Slippage %.2f bp exceeds maximum %.2f bp", result.SlippageBP, ov.config.MaxSlippage))
|
||||
}
|
||||
|
||||
// Validate net profit after gas costs
|
||||
if result.NetProfitBP <= 0 {
|
||||
result.Valid = false
|
||||
result.ValidationNotes = append(result.ValidationNotes,
|
||||
fmt.Sprintf("Net profit %.2f bp not profitable after gas costs", result.NetProfitBP))
|
||||
}
|
||||
|
||||
// Additional exchange-specific validations
|
||||
if err := ov.validateExchangeSpecific(opportunity); err != nil {
|
||||
result.Valid = false
|
||||
result.ValidationNotes = append(result.ValidationNotes, fmt.Sprintf("Exchange validation failed: %v", err))
|
||||
}
|
||||
|
||||
// If no validation errors, mark as valid
|
||||
if len(result.ValidationNotes) == 0 {
|
||||
result.Valid = true
|
||||
result.ValidationNotes = append(result.ValidationNotes, "All validations passed")
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
type TestOpportunity struct {
|
||||
ID string
|
||||
Exchange1 string
|
||||
Exchange2 string
|
||||
TokenA string
|
||||
TokenB string
|
||||
Price1 *big.Float
|
||||
Price2 *big.Float
|
||||
Liquidity *big.Float
|
||||
GasLimit uint64
|
||||
}
|
||||
|
||||
type ProfitCalculation struct {
|
||||
ProfitBP float64
|
||||
SlippageBP float64
|
||||
GasCostETH float64
|
||||
NetProfitBP float64
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) calculateProfit(opportunity *TestOpportunity) (*ProfitCalculation, error) {
|
||||
// Convert prices to UniversalDecimal for precise calculations
|
||||
price1UD, err := math.NewUniversalDecimal(opportunity.Price1, 18)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert price1: %w", err)
|
||||
}
|
||||
|
||||
price2UD, err := math.NewUniversalDecimal(opportunity.Price2, 18)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert price2: %w", err)
|
||||
}
|
||||
|
||||
// Calculate profit basis points
|
||||
priceDiff := price2UD.Sub(price1UD)
|
||||
profitRatio := priceDiff.Div(price1UD)
|
||||
profitBP := profitRatio.Mul(math.NewUniversalDecimalFromFloat(10000, 18)).Float64()
|
||||
|
||||
// Estimate slippage based on liquidity
|
||||
liquidityUD, err := math.NewUniversalDecimal(opportunity.Liquidity, 18)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert liquidity: %w", err)
|
||||
}
|
||||
|
||||
// Simple slippage model: inversely proportional to liquidity
|
||||
baseSlippage := 10.0 // 10 bp base slippage
|
||||
liquidityFactor := liquidityUD.Float64() / 1000000.0 // Normalize to millions
|
||||
slippageBP := baseSlippage / (1.0 + liquidityFactor)
|
||||
|
||||
// Estimate gas cost (simplified)
|
||||
gasPriceGwei := 0.5 // 0.5 gwei on Arbitrum
|
||||
gasCostETH := float64(opportunity.GasLimit) * gasPriceGwei * 1e-9
|
||||
|
||||
// Convert gas cost to basis points (assuming 1 ETH trade size)
|
||||
gasCostBP := gasCostETH * 10000.0
|
||||
|
||||
// Calculate net profit
|
||||
netProfitBP := profitBP - slippageBP - gasCostBP
|
||||
|
||||
return &ProfitCalculation{
|
||||
ProfitBP: profitBP,
|
||||
SlippageBP: slippageBP,
|
||||
GasCostETH: gasCostETH,
|
||||
NetProfitBP: netProfitBP,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) validateExchangeSpecific(opportunity *TestOpportunity) error {
|
||||
// Validate exchange-specific constraints
|
||||
switch opportunity.Exchange1 {
|
||||
case "uniswap_v2":
|
||||
return ov.validateUniswapV2(opportunity)
|
||||
case "uniswap_v3":
|
||||
return ov.validateUniswapV3(opportunity)
|
||||
case "curve":
|
||||
return ov.validateCurve(opportunity)
|
||||
case "balancer":
|
||||
return ov.validateBalancer(opportunity)
|
||||
default:
|
||||
return fmt.Errorf("unsupported exchange: %s", opportunity.Exchange1)
|
||||
}
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) validateUniswapV2(opportunity *TestOpportunity) error {
|
||||
// Uniswap V2 specific validations
|
||||
if opportunity.Price1.Cmp(big.NewFloat(0)) <= 0 {
|
||||
return fmt.Errorf("invalid price for Uniswap V2")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) validateUniswapV3(opportunity *TestOpportunity) error {
|
||||
// Uniswap V3 specific validations
|
||||
if opportunity.Liquidity.Cmp(big.NewFloat(0)) <= 0 {
|
||||
return fmt.Errorf("insufficient liquidity for Uniswap V3")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) validateCurve(opportunity *TestOpportunity) error {
|
||||
// Curve specific validations
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) validateBalancer(opportunity *TestOpportunity) error {
|
||||
// Balancer specific validations
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) generateTestOpportunities() []*TestOpportunity {
|
||||
opportunities := make([]*TestOpportunity, 0)
|
||||
|
||||
// ETH/USDC opportunities across different exchanges
|
||||
opportunities = append(opportunities, &TestOpportunity{
|
||||
ID: "test_eth_usdc_uniswap_v2_v3",
|
||||
Exchange1: "uniswap_v2",
|
||||
Exchange2: "uniswap_v3",
|
||||
TokenA: "ETH",
|
||||
TokenB: "USDC",
|
||||
Price1: big.NewFloat(2000.0),
|
||||
Price2: big.NewFloat(2002.5),
|
||||
Liquidity: big.NewFloat(5000000.0),
|
||||
GasLimit: 150000,
|
||||
})
|
||||
|
||||
opportunities = append(opportunities, &TestOpportunity{
|
||||
ID: "test_eth_usdc_curve_balancer",
|
||||
Exchange1: "curve",
|
||||
Exchange2: "balancer",
|
||||
TokenA: "ETH",
|
||||
TokenB: "USDC",
|
||||
Price1: big.NewFloat(2001.0),
|
||||
Price2: big.NewFloat(2004.0),
|
||||
Liquidity: big.NewFloat(10000000.0),
|
||||
GasLimit: 180000,
|
||||
})
|
||||
|
||||
// WBTC/ETH opportunities
|
||||
opportunities = append(opportunities, &TestOpportunity{
|
||||
ID: "test_wbtc_eth_uniswap",
|
||||
Exchange1: "uniswap_v2",
|
||||
Exchange2: "uniswap_v3",
|
||||
TokenA: "WBTC",
|
||||
TokenB: "ETH",
|
||||
Price1: big.NewFloat(15.5),
|
||||
Price2: big.NewFloat(15.52),
|
||||
Liquidity: big.NewFloat(2000000.0),
|
||||
GasLimit: 200000,
|
||||
})
|
||||
|
||||
// Low profit opportunity (should fail validation)
|
||||
opportunities = append(opportunities, &TestOpportunity{
|
||||
ID: "test_low_profit",
|
||||
Exchange1: "uniswap_v2",
|
||||
Exchange2: "curve",
|
||||
TokenA: "USDC",
|
||||
TokenB: "USDT",
|
||||
Price1: big.NewFloat(1.0),
|
||||
Price2: big.NewFloat(1.0005),
|
||||
Liquidity: big.NewFloat(1000000.0),
|
||||
GasLimit: 120000,
|
||||
})
|
||||
|
||||
// High slippage opportunity (should fail validation)
|
||||
opportunities = append(opportunities, &TestOpportunity{
|
||||
ID: "test_high_slippage",
|
||||
Exchange1: "uniswap_v3",
|
||||
Exchange2: "balancer",
|
||||
TokenA: "ETH",
|
||||
TokenB: "RARE_TOKEN",
|
||||
Price1: big.NewFloat(100.0),
|
||||
Price2: big.NewFloat(105.0),
|
||||
Liquidity: big.NewFloat(10000.0), // Low liquidity
|
||||
GasLimit: 250000,
|
||||
})
|
||||
|
||||
return opportunities
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) generateRealWorldScenarios() []*TestOpportunity {
|
||||
// Generate more realistic scenarios based on actual market conditions
|
||||
return []*TestOpportunity{
|
||||
{
|
||||
ID: "real_eth_usdc_arbitrum",
|
||||
Exchange1: "uniswap_v3",
|
||||
Exchange2: "curve",
|
||||
TokenA: "ETH",
|
||||
TokenB: "USDC",
|
||||
Price1: big.NewFloat(2456.78),
|
||||
Price2: big.NewFloat(2459.12),
|
||||
Liquidity: big.NewFloat(8500000.0),
|
||||
GasLimit: 165000,
|
||||
},
|
||||
{
|
||||
ID: "real_wbtc_eth_arbitrum",
|
||||
Exchange1: "balancer",
|
||||
Exchange2: "uniswap_v2",
|
||||
TokenA: "WBTC",
|
||||
TokenB: "ETH",
|
||||
Price1: big.NewFloat(16.234),
|
||||
Price2: big.NewFloat(16.251),
|
||||
Liquidity: big.NewFloat(3200000.0),
|
||||
GasLimit: 195000,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) updateStatistics(result OpportunityResult) {
|
||||
ov.results.TotalOpportunities++
|
||||
|
||||
if result.Valid {
|
||||
ov.results.ValidOpportunities++
|
||||
} else {
|
||||
ov.results.InvalidOpportunities++
|
||||
}
|
||||
|
||||
// Update exchange breakdown
|
||||
ov.results.ExchangeBreakdown[result.Exchange1]++
|
||||
ov.results.ExchangeBreakdown[result.Exchange2]++
|
||||
|
||||
// Update profit statistics
|
||||
if result.Valid && result.ProfitBP > 0 {
|
||||
if ov.results.MaxProfitBP < result.ProfitBP {
|
||||
ov.results.MaxProfitBP = result.ProfitBP
|
||||
}
|
||||
|
||||
// Calculate running average
|
||||
totalProfit := ov.results.AverageProfitBP * float64(ov.results.ValidOpportunities-1)
|
||||
ov.results.AverageProfitBP = (totalProfit + result.ProfitBP) / float64(ov.results.ValidOpportunities)
|
||||
}
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) addValidationError(errorType, message, exchange, tokenPair string) {
|
||||
ov.results.ValidationErrors = append(ov.results.ValidationErrors, ValidationError{
|
||||
Type: errorType,
|
||||
Message: message,
|
||||
Exchange: exchange,
|
||||
TokenPair: tokenPair,
|
||||
Timestamp: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) MonitorOpportunities(ctx context.Context) error {
|
||||
if ov.config.Verbose {
|
||||
fmt.Println("Starting real-time opportunity monitoring...")
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(30 * time.Second) // Check every 30 seconds
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
// Reset results for new monitoring cycle
|
||||
ov.results = &ValidationResults{
|
||||
OpportunityDetails: make([]OpportunityResult, 0),
|
||||
ExchangeBreakdown: make(map[string]int),
|
||||
ValidationErrors: make([]ValidationError, 0),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := ov.validateRealOpportunities(ctx); err != nil {
|
||||
log.Printf("Error during opportunity validation: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
if err := ov.GenerateReport(); err != nil {
|
||||
log.Printf("Error generating report: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
if ov.config.Verbose {
|
||||
fmt.Printf("Monitoring cycle complete. Found %d valid opportunities out of %d total\n",
|
||||
ov.results.ValidOpportunities, ov.results.TotalOpportunities)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) GenerateReport() error {
|
||||
// Sort opportunities by profit (descending)
|
||||
sort.Slice(ov.results.OpportunityDetails, func(i, j int) bool {
|
||||
return ov.results.OpportunityDetails[i].ProfitBP > ov.results.OpportunityDetails[j].ProfitBP
|
||||
})
|
||||
|
||||
// Generate JSON report
|
||||
jsonReport, err := json.MarshalIndent(ov.results, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal results: %w", err)
|
||||
}
|
||||
|
||||
// Save JSON report
|
||||
timestamp := time.Now().Format("2006-01-02_15-04-05")
|
||||
jsonPath := filepath.Join(ov.config.OutputDir, fmt.Sprintf("opportunity_validation_%s.json", timestamp))
|
||||
if err := os.WriteFile(jsonPath, jsonReport, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write JSON report: %w", err)
|
||||
}
|
||||
|
||||
// Generate summary report
|
||||
summaryPath := filepath.Join(ov.config.OutputDir, fmt.Sprintf("opportunity_summary_%s.txt", timestamp))
|
||||
if err := ov.generateSummaryReport(summaryPath); err != nil {
|
||||
return fmt.Errorf("failed to generate summary report: %w", err)
|
||||
}
|
||||
|
||||
if ov.config.Verbose {
|
||||
fmt.Printf("Reports generated:\n")
|
||||
fmt.Printf(" JSON: %s\n", jsonPath)
|
||||
fmt.Printf(" Summary: %s\n", summaryPath)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ov *OpportunityValidator) generateSummaryReport(filePath string) error {
|
||||
summary := fmt.Sprintf(`Arbitrage Opportunity Validation Report
|
||||
Generated: %s
|
||||
Duration: %d ms
|
||||
|
||||
SUMMARY
|
||||
=======
|
||||
Total Opportunities Analyzed: %d
|
||||
Valid Opportunities: %d
|
||||
Invalid Opportunities: %d
|
||||
Success Rate: %.1f%%
|
||||
|
||||
PROFIT STATISTICS
|
||||
================
|
||||
Average Profit: %.2f bp
|
||||
Maximum Profit: %.2f bp
|
||||
|
||||
EXCHANGE BREAKDOWN
|
||||
==================
|
||||
`, ov.results.Timestamp.Format("2006-01-02 15:04:05"),
|
||||
ov.results.DurationMs,
|
||||
ov.results.TotalOpportunities,
|
||||
ov.results.ValidOpportunities,
|
||||
ov.results.InvalidOpportunities,
|
||||
float64(ov.results.ValidOpportunities)/float64(ov.results.TotalOpportunities)*100,
|
||||
ov.results.AverageProfitBP,
|
||||
ov.results.MaxProfitBP)
|
||||
|
||||
for exchange, count := range ov.results.ExchangeBreakdown {
|
||||
summary += fmt.Sprintf("%s: %d opportunities\n", exchange, count)
|
||||
}
|
||||
|
||||
summary += "\nTOP OPPORTUNITIES\n=================\n"
|
||||
for i, opp := range ov.results.OpportunityDetails {
|
||||
if i >= 5 { // Show top 5
|
||||
break
|
||||
}
|
||||
status := "INVALID"
|
||||
if opp.Valid {
|
||||
status = "VALID"
|
||||
}
|
||||
summary += fmt.Sprintf("%d. %s (%s/%s) - %.2f bp - %s\n",
|
||||
i+1, opp.ID, opp.Exchange1, opp.Exchange2, opp.ProfitBP, status)
|
||||
}
|
||||
|
||||
if len(ov.results.ValidationErrors) > 0 {
|
||||
summary += "\nVALIDATION ERRORS\n================\n"
|
||||
for _, err := range ov.results.ValidationErrors {
|
||||
summary += fmt.Sprintf("- %s: %s\n", err.Type, err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
return os.WriteFile(filePath, []byte(summary), 0644)
|
||||
}
|
||||
69
orig/tools/opportunity-validator/main.go
Normal file
69
orig/tools/opportunity-validator/main.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/opportunity-validator/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
exchanges = flag.String("exchanges", "uniswap_v2,uniswap_v3,curve,balancer", "Comma-separated list of exchanges")
|
||||
minProfitBP = flag.Float64("min-profit", 10.0, "Minimum profit threshold in basis points")
|
||||
maxSlippage = flag.Float64("max-slippage", 100.0, "Maximum slippage in basis points")
|
||||
outputDir = flag.String("output", "reports/opportunities", "Output directory")
|
||||
verbose = flag.Bool("verbose", false, "Enable verbose output")
|
||||
realtime = flag.Bool("realtime", false, "Enable real-time opportunity monitoring")
|
||||
duration = flag.Duration("duration", 10*time.Minute, "Duration for real-time monitoring")
|
||||
dryRun = flag.Bool("dry-run", true, "Perform dry run without actual execution")
|
||||
testMode = flag.Bool("test", false, "Run in test mode with simulated data")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
// Create output directory
|
||||
if err := os.MkdirAll(*outputDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Initialize opportunity validator
|
||||
validator, err := internal.NewOpportunityValidator(&internal.ValidatorConfig{
|
||||
Exchanges: *exchanges,
|
||||
MinProfitBP: *minProfitBP,
|
||||
MaxSlippage: *maxSlippage,
|
||||
OutputDir: *outputDir,
|
||||
Verbose: *verbose,
|
||||
DryRun: *dryRun,
|
||||
TestMode: *testMode,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize validator: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
if *realtime {
|
||||
fmt.Printf("Starting real-time opportunity validation for %v...\n", *duration)
|
||||
ctx, cancel := context.WithTimeout(ctx, *duration)
|
||||
defer cancel()
|
||||
|
||||
if err := validator.MonitorOpportunities(ctx); err != nil {
|
||||
log.Fatalf("Real-time monitoring failed: %v", err)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Running opportunity validation audit...\n")
|
||||
if err := validator.ValidateOpportunities(ctx); err != nil {
|
||||
log.Fatalf("Opportunity validation failed: %v", err)
|
||||
}
|
||||
|
||||
if err := validator.GenerateReport(); err != nil {
|
||||
log.Fatalf("Report generation failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("Opportunity validation complete. Reports saved to: %s\n", *outputDir)
|
||||
}
|
||||
7
orig/tools/performance-audit/go.mod
Normal file
7
orig/tools/performance-audit/go.mod
Normal file
@@ -0,0 +1,7 @@
|
||||
module github.com/fraktal/mev-beta/tools/performance-audit
|
||||
|
||||
go 1.24
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../../
|
||||
|
||||
require github.com/fraktal/mev-beta v0.0.0-00010101000000-000000000000
|
||||
1384
orig/tools/performance-audit/internal/performance_auditor.go
Normal file
1384
orig/tools/performance-audit/internal/performance_auditor.go
Normal file
File diff suppressed because it is too large
Load Diff
69
orig/tools/performance-audit/main.go
Normal file
69
orig/tools/performance-audit/main.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/performance-audit/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
testType = flag.String("test", "all", "Test type: throughput, latency, memory, cpu, stress, all")
|
||||
duration = flag.Duration("duration", 5*time.Minute, "Test duration")
|
||||
outputDir = flag.String("output", "reports/performance", "Output directory")
|
||||
verbose = flag.Bool("verbose", false, "Enable verbose output")
|
||||
concurrent = flag.Int("concurrent", 10, "Number of concurrent workers")
|
||||
loadLevel = flag.String("load", "normal", "Load level: light, normal, heavy, extreme")
|
||||
profileEnabled = flag.Bool("profile", false, "Enable CPU/memory profiling")
|
||||
benchmarkMode = flag.Bool("benchmark", false, "Run in benchmark mode")
|
||||
stressTest = flag.Bool("stress", false, "Run stress test scenarios")
|
||||
targetTPS = flag.Int("target-tps", 1000, "Target transactions per second")
|
||||
maxMemoryMB = flag.Int("max-memory", 512, "Maximum memory usage in MB")
|
||||
cpuThreshold = flag.Float64("cpu-threshold", 80.0, "CPU usage threshold percentage")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
// Create output directory
|
||||
if err := os.MkdirAll(*outputDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Initialize performance auditor
|
||||
auditor, err := internal.NewPerformanceAuditor(&internal.PerformanceAuditConfig{
|
||||
TestType: *testType,
|
||||
Duration: *duration,
|
||||
OutputDir: *outputDir,
|
||||
Verbose: *verbose,
|
||||
Concurrent: *concurrent,
|
||||
LoadLevel: *loadLevel,
|
||||
ProfileEnabled: *profileEnabled,
|
||||
BenchmarkMode: *benchmarkMode,
|
||||
StressTest: *stressTest,
|
||||
TargetTPS: *targetTPS,
|
||||
MaxMemoryMB: *maxMemoryMB,
|
||||
CPUThreshold: *cpuThreshold,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize performance auditor: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, *duration+time.Minute) // Add buffer
|
||||
defer cancel()
|
||||
|
||||
fmt.Printf("Starting performance audit: %s test for %v...\n", *testType, *duration)
|
||||
if err := auditor.RunPerformanceTests(ctx); err != nil {
|
||||
log.Fatalf("Performance audit failed: %v", err)
|
||||
}
|
||||
|
||||
if err := auditor.GenerateReport(); err != nil {
|
||||
log.Fatalf("Report generation failed: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Performance audit complete. Reports saved to: %s\n", *outputDir)
|
||||
}
|
||||
7
orig/tools/profitability-audit/go.mod
Normal file
7
orig/tools/profitability-audit/go.mod
Normal file
@@ -0,0 +1,7 @@
|
||||
module github.com/fraktal/mev-beta/tools/profitability-audit
|
||||
|
||||
go 1.24
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../../
|
||||
|
||||
require github.com/fraktal/mev-beta v0.0.0-00010101000000-000000000000
|
||||
511
orig/tools/profitability-audit/internal/profitability_auditor.go
Normal file
511
orig/tools/profitability-audit/internal/profitability_auditor.go
Normal file
@@ -0,0 +1,511 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/pkg/math"
|
||||
)
|
||||
|
||||
// Config holds configuration for the profitability auditor
|
||||
type Config struct {
|
||||
MinProfitBP float64
|
||||
MaxSlippageBP float64
|
||||
OutputDir string
|
||||
Verbose bool
|
||||
ScenariosFile string
|
||||
}
|
||||
|
||||
// ProfitabilityAuditor audits profit calculations and arbitrage opportunities
|
||||
type ProfitabilityAuditor struct {
|
||||
config *Config
|
||||
converter *math.DecimalConverter
|
||||
calculator *math.ArbitrageCalculator
|
||||
scenarios *ProfitabilityScenarios
|
||||
results map[string]*ExchangeProfitResult
|
||||
}
|
||||
|
||||
// ProfitabilityScenarios defines test scenarios for profit validation
|
||||
type ProfitabilityScenarios struct {
|
||||
Version string `json:"version"`
|
||||
Scenarios map[string]*ProfitabilityTest `json:"scenarios"`
|
||||
}
|
||||
|
||||
// ProfitabilityTest represents a profit calculation test case
|
||||
type ProfitabilityTest struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Exchange string `json:"exchange"`
|
||||
AmountIn string `json:"amount_in"`
|
||||
TokenIn string `json:"token_in"`
|
||||
TokenOut string `json:"token_out"`
|
||||
ExpectedProfit string `json:"expected_profit"`
|
||||
MaxSlippage float64 `json:"max_slippage"`
|
||||
GasCost string `json:"gas_cost"`
|
||||
MinROI float64 `json:"min_roi"`
|
||||
TestType string `json:"test_type"` // "static", "stress", "edge_case"
|
||||
}
|
||||
|
||||
// ExchangeProfitResult holds profitability audit results for an exchange
|
||||
type ExchangeProfitResult struct {
|
||||
Exchange string `json:"exchange"`
|
||||
TotalTests int `json:"total_tests"`
|
||||
PassedTests int `json:"passed_tests"`
|
||||
FailedTests int `json:"failed_tests"`
|
||||
AverageProfitBP float64 `json:"average_profit_bp"`
|
||||
MaxProfitBP float64 `json:"max_profit_bp"`
|
||||
MinProfitBP float64 `json:"min_profit_bp"`
|
||||
AverageROI float64 `json:"average_roi"`
|
||||
TestResults []*ProfitTestResult `json:"test_results"`
|
||||
FailedCases []*ProfitTestFailure `json:"failed_cases"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// ProfitTestResult represents the result of a single profit test
|
||||
type ProfitTestResult struct {
|
||||
TestName string `json:"test_name"`
|
||||
Passed bool `json:"passed"`
|
||||
ActualProfitBP float64 `json:"actual_profit_bp"`
|
||||
ExpectedProfitBP float64 `json:"expected_profit_bp"`
|
||||
ActualROI float64 `json:"actual_roi"`
|
||||
ExpectedROI float64 `json:"expected_roi"`
|
||||
SlippageBP float64 `json:"slippage_bp"`
|
||||
GasCostETH string `json:"gas_cost_eth"`
|
||||
NetProfitETH string `json:"net_profit_eth"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
}
|
||||
|
||||
// ProfitTestFailure represents a failed profit test
|
||||
type ProfitTestFailure struct {
|
||||
TestName string `json:"test_name"`
|
||||
Reason string `json:"reason"`
|
||||
Expected float64 `json:"expected"`
|
||||
Actual float64 `json:"actual"`
|
||||
Difference float64 `json:"difference"`
|
||||
Severity string `json:"severity"` // "low", "medium", "high", "critical"
|
||||
}
|
||||
|
||||
// NewProfitabilityAuditor creates a new profitability auditor
|
||||
func NewProfitabilityAuditor(config *Config) (*ProfitabilityAuditor, error) {
|
||||
converter := math.NewDecimalConverter()
|
||||
calculator := math.NewArbitrageCalculator(nil) // TODO: Add proper gas estimator
|
||||
|
||||
// Load test scenarios
|
||||
scenarios, err := loadProfitabilityScenarios(config.ScenariosFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load scenarios: %w", err)
|
||||
}
|
||||
|
||||
return &ProfitabilityAuditor{
|
||||
config: config,
|
||||
converter: converter,
|
||||
calculator: calculator,
|
||||
scenarios: scenarios,
|
||||
results: make(map[string]*ExchangeProfitResult),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// AuditExchange performs profitability audit for a specific exchange
|
||||
func (pa *ProfitabilityAuditor) AuditExchange(ctx context.Context, exchange string) error {
|
||||
startTime := time.Now()
|
||||
|
||||
if pa.config.Verbose {
|
||||
fmt.Printf("Starting profitability audit for %s...\n", exchange)
|
||||
}
|
||||
|
||||
result := &ExchangeProfitResult{
|
||||
Exchange: exchange,
|
||||
TestResults: []*ProfitTestResult{},
|
||||
FailedCases: []*ProfitTestFailure{},
|
||||
Timestamp: startTime,
|
||||
}
|
||||
|
||||
// Get scenarios for this exchange
|
||||
exchangeScenarios := pa.getExchangeScenarios(exchange)
|
||||
result.TotalTests = len(exchangeScenarios)
|
||||
|
||||
var totalProfitBP, totalROI float64
|
||||
maxProfitBP := -1000.0
|
||||
minProfitBP := 1000.0
|
||||
|
||||
for _, scenario := range exchangeScenarios {
|
||||
testResult, err := pa.runProfitTest(ctx, scenario)
|
||||
if err != nil {
|
||||
if pa.config.Verbose {
|
||||
fmt.Printf(" Failed test %s: %v\n", scenario.Name, err)
|
||||
}
|
||||
|
||||
failure := &ProfitTestFailure{
|
||||
TestName: scenario.Name,
|
||||
Reason: err.Error(),
|
||||
Severity: "high",
|
||||
}
|
||||
result.FailedCases = append(result.FailedCases, failure)
|
||||
result.FailedTests++
|
||||
continue
|
||||
}
|
||||
|
||||
result.TestResults = append(result.TestResults, testResult)
|
||||
|
||||
if testResult.Passed {
|
||||
result.PassedTests++
|
||||
totalProfitBP += testResult.ActualProfitBP
|
||||
totalROI += testResult.ActualROI
|
||||
|
||||
if testResult.ActualProfitBP > maxProfitBP {
|
||||
maxProfitBP = testResult.ActualProfitBP
|
||||
}
|
||||
if testResult.ActualProfitBP < minProfitBP {
|
||||
minProfitBP = testResult.ActualProfitBP
|
||||
}
|
||||
} else {
|
||||
result.FailedTests++
|
||||
|
||||
failure := &ProfitTestFailure{
|
||||
TestName: scenario.Name,
|
||||
Reason: testResult.ErrorMessage,
|
||||
Expected: testResult.ExpectedProfitBP,
|
||||
Actual: testResult.ActualProfitBP,
|
||||
Difference: testResult.ActualProfitBP - testResult.ExpectedProfitBP,
|
||||
Severity: pa.calculateSeverity(testResult.ActualProfitBP, testResult.ExpectedProfitBP),
|
||||
}
|
||||
result.FailedCases = append(result.FailedCases, failure)
|
||||
}
|
||||
|
||||
if pa.config.Verbose {
|
||||
status := "✓"
|
||||
if !testResult.Passed {
|
||||
status = "✗"
|
||||
}
|
||||
fmt.Printf(" %s %s: Profit=%.2f bp, ROI=%.2f%%\n",
|
||||
status, scenario.Name, testResult.ActualProfitBP, testResult.ActualROI)
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate averages
|
||||
if result.PassedTests > 0 {
|
||||
result.AverageProfitBP = totalProfitBP / float64(result.PassedTests)
|
||||
result.AverageROI = totalROI / float64(result.PassedTests)
|
||||
result.MaxProfitBP = maxProfitBP
|
||||
result.MinProfitBP = minProfitBP
|
||||
}
|
||||
|
||||
result.Duration = time.Since(startTime)
|
||||
pa.results[exchange] = result
|
||||
|
||||
if pa.config.Verbose {
|
||||
fmt.Printf("Completed %s audit: %d/%d tests passed (%.1f%%)\n",
|
||||
exchange, result.PassedTests, result.TotalTests,
|
||||
float64(result.PassedTests)/float64(result.TotalTests)*100)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// runProfitTest executes a single profit test
|
||||
func (pa *ProfitabilityAuditor) runProfitTest(ctx context.Context, scenario *ProfitabilityTest) (*ProfitTestResult, error) {
|
||||
startTime := time.Now()
|
||||
|
||||
// Convert input amounts to UniversalDecimal
|
||||
amountIn, err := pa.converter.FromString(scenario.AmountIn, 18, scenario.TokenIn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid amount_in: %w", err)
|
||||
}
|
||||
|
||||
gasCost, err := pa.converter.FromString(scenario.GasCost, 18, "ETH")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid gas_cost: %w", err)
|
||||
}
|
||||
|
||||
expectedProfit, err := pa.converter.FromString(scenario.ExpectedProfit, 18, "ETH")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid expected_profit: %w", err)
|
||||
}
|
||||
|
||||
// Simulate arbitrage calculation
|
||||
// TODO: Integrate with actual exchange data and calculation engine
|
||||
actualProfit, netProfit, slippage, err := pa.simulateProfitCalculation(scenario, amountIn, gasCost)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("profit simulation failed: %w", err)
|
||||
}
|
||||
|
||||
// Calculate metrics
|
||||
actualProfitBP := pa.calculateProfitBP(actualProfit, amountIn)
|
||||
expectedProfitBP := pa.calculateProfitBP(expectedProfit, amountIn)
|
||||
actualROI := actualProfitBP / 100.0 // Convert BP to percentage
|
||||
|
||||
// Determine if test passed
|
||||
profitDiff := actualProfitBP - expectedProfitBP
|
||||
profitPassed := actualProfitBP >= pa.config.MinProfitBP
|
||||
slippagePassed := slippage <= pa.config.MaxSlippageBP
|
||||
roiPassed := actualROI >= scenario.MinROI
|
||||
|
||||
passed := profitPassed && slippagePassed && roiPassed
|
||||
|
||||
result := &ProfitTestResult{
|
||||
TestName: scenario.Name,
|
||||
Passed: passed,
|
||||
ActualProfitBP: actualProfitBP,
|
||||
ExpectedProfitBP: expectedProfitBP,
|
||||
ActualROI: actualROI,
|
||||
ExpectedROI: scenario.MinROI,
|
||||
SlippageBP: slippage,
|
||||
GasCostETH: pa.converter.ToHumanReadable(gasCost),
|
||||
NetProfitETH: pa.converter.ToHumanReadable(netProfit),
|
||||
Duration: time.Since(startTime),
|
||||
}
|
||||
|
||||
if !passed {
|
||||
var reasons []string
|
||||
if !profitPassed {
|
||||
reasons = append(reasons, fmt.Sprintf("profit %.2f bp below minimum %.2f bp", actualProfitBP, pa.config.MinProfitBP))
|
||||
}
|
||||
if !slippagePassed {
|
||||
reasons = append(reasons, fmt.Sprintf("slippage %.2f bp exceeds maximum %.2f bp", slippage, pa.config.MaxSlippageBP))
|
||||
}
|
||||
if !roiPassed {
|
||||
reasons = append(reasons, fmt.Sprintf("ROI %.2f%% below minimum %.2f%%", actualROI, scenario.MinROI))
|
||||
}
|
||||
result.ErrorMessage = fmt.Sprintf("Test failed: %v", reasons)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// simulateProfitCalculation simulates profit calculation for a scenario
|
||||
func (pa *ProfitabilityAuditor) simulateProfitCalculation(scenario *ProfitabilityTest, amountIn, gasCost *math.UniversalDecimal) (*math.UniversalDecimal, *math.UniversalDecimal, float64, error) {
|
||||
// This is a simplified simulation - in production, this would integrate with real exchange APIs
|
||||
|
||||
// Simulate price impact and slippage based on exchange type
|
||||
var slippageBP float64
|
||||
var profitMultiplier float64
|
||||
|
||||
switch scenario.Exchange {
|
||||
case "uniswap_v2":
|
||||
slippageBP = 15.0 // Simulate 15 bp slippage
|
||||
profitMultiplier = 1.025 // 2.5% profit
|
||||
case "uniswap_v3":
|
||||
slippageBP = 8.0 // Lower slippage for V3
|
||||
profitMultiplier = 1.032 // 3.2% profit
|
||||
case "curve":
|
||||
slippageBP = 3.0 // Very low slippage for stable swaps
|
||||
profitMultiplier = 1.008 // 0.8% profit
|
||||
case "balancer":
|
||||
slippageBP = 25.0 // Higher slippage for weighted pools
|
||||
profitMultiplier = 1.045 // 4.5% profit
|
||||
default:
|
||||
return nil, nil, 0, fmt.Errorf("unsupported exchange: %s", scenario.Exchange)
|
||||
}
|
||||
|
||||
// Calculate gross profit
|
||||
profitAmount := new(big.Int).Mul(amountIn.Value, big.NewInt(int64(profitMultiplier*1000)))
|
||||
profitAmount.Div(profitAmount, big.NewInt(1000))
|
||||
profitAmount.Sub(profitAmount, amountIn.Value)
|
||||
|
||||
grossProfit, err := math.NewUniversalDecimal(profitAmount, 18, "ETH")
|
||||
if err != nil {
|
||||
return nil, nil, 0, err
|
||||
}
|
||||
|
||||
// Calculate net profit (gross - gas)
|
||||
netProfitAmount := new(big.Int).Sub(grossProfit.Value, gasCost.Value)
|
||||
netProfit, err := math.NewUniversalDecimal(netProfitAmount, 18, "ETH")
|
||||
if err != nil {
|
||||
return nil, nil, 0, err
|
||||
}
|
||||
|
||||
return grossProfit, netProfit, slippageBP, nil
|
||||
}
|
||||
|
||||
// calculateProfitBP calculates profit in basis points
|
||||
func (pa *ProfitabilityAuditor) calculateProfitBP(profit, amountIn *math.UniversalDecimal) float64 {
|
||||
if amountIn.Value.Cmp(big.NewInt(0)) == 0 {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
// Convert to float for calculation
|
||||
profitFloat, _ := new(big.Float).SetInt(profit.Value).Float64()
|
||||
amountFloat, _ := new(big.Float).SetInt(amountIn.Value).Float64()
|
||||
|
||||
return (profitFloat / amountFloat) * 10000.0 // Convert to basis points
|
||||
}
|
||||
|
||||
// calculateSeverity determines the severity of a test failure
|
||||
func (pa *ProfitabilityAuditor) calculateSeverity(actual, expected float64) string {
|
||||
diff := expected - actual
|
||||
diffPercent := (diff / expected) * 100
|
||||
|
||||
switch {
|
||||
case diffPercent > 50:
|
||||
return "critical"
|
||||
case diffPercent > 25:
|
||||
return "high"
|
||||
case diffPercent > 10:
|
||||
return "medium"
|
||||
default:
|
||||
return "low"
|
||||
}
|
||||
}
|
||||
|
||||
// getExchangeScenarios returns test scenarios for a specific exchange
|
||||
func (pa *ProfitabilityAuditor) getExchangeScenarios(exchange string) []*ProfitabilityTest {
|
||||
var scenarios []*ProfitabilityTest
|
||||
|
||||
for _, scenario := range pa.scenarios.Scenarios {
|
||||
if scenario.Exchange == exchange || scenario.Exchange == "all" {
|
||||
scenarios = append(scenarios, scenario)
|
||||
}
|
||||
}
|
||||
|
||||
// If no scenarios found, create default ones
|
||||
if len(scenarios) == 0 {
|
||||
scenarios = pa.createDefaultScenarios(exchange)
|
||||
}
|
||||
|
||||
return scenarios
|
||||
}
|
||||
|
||||
// createDefaultScenarios creates default test scenarios for an exchange
|
||||
func (pa *ProfitabilityAuditor) createDefaultScenarios(exchange string) []*ProfitabilityTest {
|
||||
baseScenarios := []*ProfitabilityTest{
|
||||
{
|
||||
Name: fmt.Sprintf("%s_small_arbitrage", exchange),
|
||||
Description: "Small arbitrage opportunity",
|
||||
Exchange: exchange,
|
||||
AmountIn: "1000000000000000000", // 1 ETH
|
||||
TokenIn: "ETH",
|
||||
TokenOut: "USDC",
|
||||
ExpectedProfit: "25000000000000000", // 0.025 ETH
|
||||
MaxSlippage: 50.0,
|
||||
GasCost: "5000000000000000", // 0.005 ETH
|
||||
MinROI: 1.0,
|
||||
TestType: "static",
|
||||
},
|
||||
{
|
||||
Name: fmt.Sprintf("%s_medium_arbitrage", exchange),
|
||||
Description: "Medium arbitrage opportunity",
|
||||
Exchange: exchange,
|
||||
AmountIn: "10000000000000000000", // 10 ETH
|
||||
TokenIn: "ETH",
|
||||
TokenOut: "USDC",
|
||||
ExpectedProfit: "300000000000000000", // 0.3 ETH
|
||||
MaxSlippage: 100.0,
|
||||
GasCost: "8000000000000000", // 0.008 ETH
|
||||
MinROI: 2.5,
|
||||
TestType: "static",
|
||||
},
|
||||
{
|
||||
Name: fmt.Sprintf("%s_large_arbitrage", exchange),
|
||||
Description: "Large arbitrage opportunity",
|
||||
Exchange: exchange,
|
||||
AmountIn: "100000000000000000000", // 100 ETH
|
||||
TokenIn: "ETH",
|
||||
TokenOut: "USDC",
|
||||
ExpectedProfit: "5000000000000000000", // 5 ETH
|
||||
MaxSlippage: 200.0,
|
||||
GasCost: "15000000000000000", // 0.015 ETH
|
||||
MinROI: 4.5,
|
||||
TestType: "stress",
|
||||
},
|
||||
}
|
||||
|
||||
return baseScenarios
|
||||
}
|
||||
|
||||
// MonitorRealTimeProfit monitors real-time profit opportunities
|
||||
func (pa *ProfitabilityAuditor) MonitorRealTimeProfit(ctx context.Context, exchange string) error {
|
||||
// TODO: Implement real-time monitoring with live market data
|
||||
ticker := time.NewTicker(10 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
fmt.Printf("Monitoring real-time profitability for %s...\n", exchange)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
// Simulate real-time profit check
|
||||
if pa.config.Verbose {
|
||||
fmt.Printf("[%s] Checking real-time opportunities for %s...\n",
|
||||
time.Now().Format("15:04:05"), exchange)
|
||||
}
|
||||
|
||||
// TODO: Integrate with live market data and opportunity detection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateReport generates comprehensive profitability audit reports
|
||||
func (pa *ProfitabilityAuditor) GenerateReport() error {
|
||||
// Generate JSON report
|
||||
reportPath := filepath.Join(pa.config.OutputDir, "profitability_audit.json")
|
||||
if err := pa.generateJSONReport(reportPath); err != nil {
|
||||
return fmt.Errorf("failed to generate JSON report: %w", err)
|
||||
}
|
||||
|
||||
// Generate Markdown report
|
||||
markdownPath := filepath.Join(pa.config.OutputDir, "profitability_audit.md")
|
||||
if err := pa.generateMarkdownReport(markdownPath); err != nil {
|
||||
return fmt.Errorf("failed to generate Markdown report: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// generateJSONReport generates a JSON format report
|
||||
func (pa *ProfitabilityAuditor) generateJSONReport(path string) error {
|
||||
report := map[string]interface{}{
|
||||
"timestamp": time.Now(),
|
||||
"config": pa.config,
|
||||
"exchange_results": pa.results,
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(report, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(path, data, 0644)
|
||||
}
|
||||
|
||||
// generateMarkdownReport generates a Markdown format report
|
||||
func (pa *ProfitabilityAuditor) generateMarkdownReport(path string) error {
|
||||
// TODO: Implement detailed Markdown report generation
|
||||
content := fmt.Sprintf("# Profitability Audit Report\n\nGenerated: %s\n\n", time.Now().Format(time.RFC3339))
|
||||
|
||||
for exchange, result := range pa.results {
|
||||
content += fmt.Sprintf("## %s\n\n", exchange)
|
||||
content += fmt.Sprintf("- Total Tests: %d\n", result.TotalTests)
|
||||
content += fmt.Sprintf("- Passed: %d\n", result.PassedTests)
|
||||
content += fmt.Sprintf("- Failed: %d\n", result.FailedTests)
|
||||
content += fmt.Sprintf("- Average Profit: %.2f bp\n", result.AverageProfitBP)
|
||||
content += fmt.Sprintf("- Average ROI: %.2f%%\n\n", result.AverageROI)
|
||||
}
|
||||
|
||||
return os.WriteFile(path, []byte(content), 0644)
|
||||
}
|
||||
|
||||
// loadProfitabilityScenarios loads test scenarios from file
|
||||
func loadProfitabilityScenarios(filename string) (*ProfitabilityScenarios, error) {
|
||||
// If filename is "default", create default scenarios
|
||||
if filename == "default" {
|
||||
return &ProfitabilityScenarios{
|
||||
Version: "1.0.0",
|
||||
Scenarios: make(map[string]*ProfitabilityTest),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// TODO: Load from actual file
|
||||
return &ProfitabilityScenarios{
|
||||
Version: "1.0.0",
|
||||
Scenarios: make(map[string]*ProfitabilityTest),
|
||||
}, nil
|
||||
}
|
||||
90
orig/tools/profitability-audit/main.go
Normal file
90
orig/tools/profitability-audit/main.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/profitability-audit/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
exchange = flag.String("exchange", "", "Exchange to audit (uniswap_v2, uniswap_v3, curve, balancer, all)")
|
||||
minProfitBP = flag.Float64("min-profit", 10.0, "Minimum profit threshold in basis points")
|
||||
maxSlippage = flag.Float64("max-slippage", 50.0, "Maximum acceptable slippage in basis points")
|
||||
scenarios = flag.String("scenarios", "default", "Test scenarios file (default, stress, production)")
|
||||
outputDir = flag.String("output", "reports/profitability", "Output directory for reports")
|
||||
verbose = flag.Bool("verbose", false, "Enable verbose output")
|
||||
realtime = flag.Bool("realtime", false, "Enable real-time profit monitoring")
|
||||
duration = flag.Duration("duration", 5*time.Minute, "Duration for real-time monitoring")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
if *exchange == "" {
|
||||
fmt.Println("Usage: profitability-audit -exchange <exchange> [options]")
|
||||
flag.PrintDefaults()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Create output directory
|
||||
if err := os.MkdirAll(*outputDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Initialize profitability auditor
|
||||
auditor, err := internal.NewProfitabilityAuditor(&internal.Config{
|
||||
MinProfitBP: *minProfitBP,
|
||||
MaxSlippageBP: *maxSlippage,
|
||||
OutputDir: *outputDir,
|
||||
Verbose: *verbose,
|
||||
ScenariosFile: *scenarios,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize auditor: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Run profitability audit
|
||||
if *realtime {
|
||||
fmt.Printf("Starting real-time profitability monitoring for %v...\n", *duration)
|
||||
if err := runRealtimeAudit(ctx, auditor, *exchange, *duration); err != nil {
|
||||
log.Fatalf("Real-time audit failed: %v", err)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Running profitability audit for exchange: %s\n", *exchange)
|
||||
if err := runStaticAudit(ctx, auditor, *exchange); err != nil {
|
||||
log.Fatalf("Static audit failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("Audit complete. Reports saved to: %s\n", *outputDir)
|
||||
}
|
||||
|
||||
func runStaticAudit(ctx context.Context, auditor *internal.ProfitabilityAuditor, exchange string) error {
|
||||
if exchange == "all" {
|
||||
exchanges := []string{"uniswap_v2", "uniswap_v3", "curve", "balancer"}
|
||||
for _, ex := range exchanges {
|
||||
if err := auditor.AuditExchange(ctx, ex); err != nil {
|
||||
return fmt.Errorf("failed to audit %s: %w", ex, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err := auditor.AuditExchange(ctx, exchange); err != nil {
|
||||
return fmt.Errorf("failed to audit %s: %w", exchange, err)
|
||||
}
|
||||
}
|
||||
|
||||
return auditor.GenerateReport()
|
||||
}
|
||||
|
||||
func runRealtimeAudit(ctx context.Context, auditor *internal.ProfitabilityAuditor, exchange string, duration time.Duration) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, duration)
|
||||
defer cancel()
|
||||
|
||||
return auditor.MonitorRealTimeProfit(ctx, exchange)
|
||||
}
|
||||
71
orig/tools/reports/math/latest/report.json
Normal file
71
orig/tools/reports/math/latest/report.json
Normal file
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"summary": {
|
||||
"generated_at": "2025-10-20T04:27:10.896327863Z",
|
||||
"total_vectors": 1,
|
||||
"vectors_passed": 0,
|
||||
"total_assertions": 1,
|
||||
"assertions_passed": 0,
|
||||
"property_checks": 4,
|
||||
"property_succeeded": 4
|
||||
},
|
||||
"vectors": [
|
||||
{
|
||||
"name": "default_formatted",
|
||||
"description": "Default formatted test vectors for MEV Bot math validation",
|
||||
"exchange": "uniswap_v2",
|
||||
"passed": false,
|
||||
"tests": [
|
||||
{
|
||||
"name": "default_amount_out_test",
|
||||
"type": "amount_out",
|
||||
"passed": false,
|
||||
"delta_bps": 9990.009995065288,
|
||||
"expected": "0.000001994006985",
|
||||
"actual": "0.000000001992013962",
|
||||
"details": "delta 9990.0100 bps exceeds tolerance 500.0000",
|
||||
"annotations": [
|
||||
"tolerance 500.0000 bps"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"property_checks": [
|
||||
{
|
||||
"name": "price_conversion_round_trip",
|
||||
"type": "property",
|
||||
"passed": true,
|
||||
"delta_bps": 0,
|
||||
"expected": "",
|
||||
"actual": "",
|
||||
"details": "all samples within 0.1% tolerance"
|
||||
},
|
||||
{
|
||||
"name": "tick_conversion_round_trip",
|
||||
"type": "property",
|
||||
"passed": true,
|
||||
"delta_bps": 0,
|
||||
"expected": "",
|
||||
"actual": "",
|
||||
"details": "ticks round-trip within ±1"
|
||||
},
|
||||
{
|
||||
"name": "price_monotonicity",
|
||||
"type": "property",
|
||||
"passed": true,
|
||||
"delta_bps": 0,
|
||||
"expected": "",
|
||||
"actual": "",
|
||||
"details": "higher ticks produced higher prices"
|
||||
},
|
||||
{
|
||||
"name": "price_symmetry",
|
||||
"type": "property",
|
||||
"passed": true,
|
||||
"delta_bps": 0,
|
||||
"expected": "",
|
||||
"actual": "",
|
||||
"details": "price * inverse remained within 0.1%"
|
||||
}
|
||||
]
|
||||
}
|
||||
20
orig/tools/reports/math/latest/report.md
Normal file
20
orig/tools/reports/math/latest/report.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Math Audit Report
|
||||
|
||||
- Generated: 2025-10-20 04:27:10 UTC
|
||||
- Vectors: 0/1 passed
|
||||
- Assertions: 0/1 passed
|
||||
- Property checks: 4/4 passed
|
||||
|
||||
## Vector Results
|
||||
|
||||
| Vector | Exchange | Status | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| default_formatted | uniswap_v2 | ❌ FAIL | default_amount_out_test (9990.0100 bps) |
|
||||
|
||||
## Property Checks
|
||||
|
||||
- ✅ price_conversion_round_trip — all samples within 0.1% tolerance
|
||||
- ✅ tick_conversion_round_trip — ticks round-trip within ±1
|
||||
- ✅ price_monotonicity — higher ticks produced higher prices
|
||||
- ✅ price_symmetry — price * inverse remained within 0.1%
|
||||
|
||||
7
orig/tools/security-audit/go.mod
Normal file
7
orig/tools/security-audit/go.mod
Normal file
@@ -0,0 +1,7 @@
|
||||
module github.com/fraktal/mev-beta/tools/security-audit
|
||||
|
||||
go 1.24
|
||||
|
||||
replace github.com/fraktal/mev-beta => ../../
|
||||
|
||||
require github.com/fraktal/mev-beta v0.0.0-00010101000000-000000000000
|
||||
1897
orig/tools/security-audit/internal/security_auditor.go
Normal file
1897
orig/tools/security-audit/internal/security_auditor.go
Normal file
File diff suppressed because it is too large
Load Diff
67
orig/tools/security-audit/main.go
Normal file
67
orig/tools/security-audit/main.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/fraktal/mev-beta/tools/security-audit/internal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
scanType = flag.String("scan", "all", "Scan type: code, dependencies, secrets, permissions, network, all")
|
||||
outputDir = flag.String("output", "reports/security", "Output directory")
|
||||
verbose = flag.Bool("verbose", false, "Enable verbose output")
|
||||
deepScan = flag.Bool("deep", false, "Perform deep security analysis")
|
||||
includeTests = flag.Bool("include-tests", false, "Include test files in security scan")
|
||||
riskThreshold = flag.String("risk-threshold", "medium", "Risk threshold: low, medium, high, critical")
|
||||
reportFormat = flag.String("format", "json", "Report format: json, sarif, txt")
|
||||
timeout = flag.Duration("timeout", 10*time.Minute, "Timeout for security operations")
|
||||
baseline = flag.String("baseline", "", "Baseline security report for comparison")
|
||||
remediationMode = flag.Bool("remediation", false, "Include remediation suggestions")
|
||||
complianceCheck = flag.Bool("compliance", false, "Include compliance checks")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
// Create output directory
|
||||
if err := os.MkdirAll(*outputDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Initialize security auditor
|
||||
auditor, err := internal.NewSecurityAuditor(&internal.SecurityAuditConfig{
|
||||
ScanType: *scanType,
|
||||
OutputDir: *outputDir,
|
||||
Verbose: *verbose,
|
||||
DeepScan: *deepScan,
|
||||
IncludeTests: *includeTests,
|
||||
RiskThreshold: *riskThreshold,
|
||||
ReportFormat: *reportFormat,
|
||||
Timeout: *timeout,
|
||||
Baseline: *baseline,
|
||||
RemediationMode: *remediationMode,
|
||||
ComplianceCheck: *complianceCheck,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize security auditor: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := context.WithTimeout(ctx, *timeout)
|
||||
defer cancel()
|
||||
|
||||
fmt.Printf("Starting security audit: %s scan...\n", *scanType)
|
||||
if err := auditor.RunSecurityAudit(ctx); err != nil {
|
||||
log.Fatalf("Security audit failed: %v", err)
|
||||
}
|
||||
|
||||
if err := auditor.GenerateReport(); err != nil {
|
||||
log.Fatalf("Report generation failed: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Security audit complete. Reports saved to: %s\n", *outputDir)
|
||||
}
|
||||
723
orig/tools/simulation/main.go
Normal file
723
orig/tools/simulation/main.go
Normal file
@@ -0,0 +1,723 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type simulationMetadata struct {
|
||||
Network string `json:"network"`
|
||||
Window string `json:"window"`
|
||||
Sources []string `json:"sources"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
type opportunityVector struct {
|
||||
ID string `json:"id"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Exchange string `json:"exchange"`
|
||||
ExpectedProfitWei string `json:"expected_profit_wei"`
|
||||
GasCostWei string `json:"gas_cost_wei"`
|
||||
Executed bool `json:"executed"`
|
||||
RealizedProfitWei string `json:"realized_profit_wei"`
|
||||
SlippageLossWei string `json:"slippage_loss_wei"`
|
||||
SkipReason string `json:"skip_reason"`
|
||||
}
|
||||
|
||||
type simulationVectors struct {
|
||||
Metadata simulationMetadata `json:"metadata"`
|
||||
Opportunities []opportunityVector `json:"opportunities"`
|
||||
}
|
||||
|
||||
type exchangeBreakdown struct {
|
||||
Exchange string `json:"exchange"`
|
||||
Executed int `json:"executed"`
|
||||
Successful int `json:"successful"`
|
||||
HitRate float64 `json:"hit_rate"`
|
||||
GrossProfitETH string `json:"gross_profit_eth"`
|
||||
NetProfitETH string `json:"net_profit_eth"`
|
||||
GasCostETH string `json:"gas_cost_eth"`
|
||||
}
|
||||
|
||||
type skipReason struct {
|
||||
Reason string `json:"reason"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type simulationSummary struct {
|
||||
GeneratedAt string `json:"generated_at"`
|
||||
VectorPath string `json:"vector_path"`
|
||||
Network string `json:"network"`
|
||||
Window string `json:"window"`
|
||||
Sources []string `json:"sources"`
|
||||
Attempts int `json:"attempts"`
|
||||
Executed int `json:"executed"`
|
||||
ConversionRate float64 `json:"conversion_rate"`
|
||||
Successful int `json:"successful"`
|
||||
Failed int `json:"failed"`
|
||||
HitRate float64 `json:"hit_rate"`
|
||||
GrossProfitETH string `json:"gross_profit_eth"`
|
||||
GasCostETH string `json:"gas_cost_eth"`
|
||||
NetProfitETH string `json:"net_profit_eth"`
|
||||
AverageProfitETH string `json:"average_profit_per_trade_eth"`
|
||||
AverageGasCostETH string `json:"average_gas_cost_eth"`
|
||||
ProfitFactor float64 `json:"profit_factor"`
|
||||
ExchangeBreakdown []exchangeBreakdown `json:"exchange_breakdown"`
|
||||
SkipReasons []skipReason `json:"skip_reasons"`
|
||||
}
|
||||
|
||||
type payloadAnalysisReport struct {
|
||||
GeneratedAt string `json:"generated_at"`
|
||||
Directory string `json:"directory"`
|
||||
FileCount int `json:"file_count"`
|
||||
TimeRange payloadTimeRange `json:"time_range"`
|
||||
Protocols []namedCount `json:"protocols"`
|
||||
Contracts []namedCount `json:"contracts"`
|
||||
Functions []namedCount `json:"functions"`
|
||||
MissingBlockNumber int `json:"missing_block_number"`
|
||||
MissingRecipient int `json:"missing_recipient"`
|
||||
NonZeroValueCount int `json:"non_zero_value_count"`
|
||||
AverageInputBytes float64 `json:"average_input_bytes"`
|
||||
SampleTransactionHashes []string `json:"sample_transaction_hashes"`
|
||||
}
|
||||
|
||||
type payloadTimeRange struct {
|
||||
Earliest string `json:"earliest"`
|
||||
Latest string `json:"latest"`
|
||||
}
|
||||
|
||||
type namedCount struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
Percentage float64 `json:"percentage"`
|
||||
}
|
||||
|
||||
type payloadEntry struct {
|
||||
BlockNumber string `json:"block_number"`
|
||||
Contract string `json:"contract_name"`
|
||||
From string `json:"from"`
|
||||
Function string `json:"function"`
|
||||
FunctionSig string `json:"function_sig"`
|
||||
Hash string `json:"hash"`
|
||||
InputData string `json:"input_data"`
|
||||
Protocol string `json:"protocol"`
|
||||
Recipient string `json:"to"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
var weiToEthScale = big.NewRat(1, 1_000_000_000_000_000_000)
|
||||
|
||||
func main() {
|
||||
vectorsPath := flag.String("vectors", "tools/simulation/vectors/default.json", "Path to simulation vector file")
|
||||
reportDir := flag.String("report", "reports/simulation/latest", "Directory for generated reports")
|
||||
payloadDir := flag.String("payload-dir", "", "Directory containing captured opportunity payloads to analyse")
|
||||
flag.Parse()
|
||||
|
||||
var payloadAnalysis *payloadAnalysisReport
|
||||
if payloadDir != nil && *payloadDir != "" {
|
||||
analysis, err := analyzePayloads(*payloadDir)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to analyse payload captures: %v", err)
|
||||
}
|
||||
payloadAnalysis = &analysis
|
||||
}
|
||||
|
||||
dataset, err := loadVectors(*vectorsPath)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to load vectors: %v", err)
|
||||
}
|
||||
|
||||
summary, err := computeSummary(*vectorsPath, dataset)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to compute summary: %v", err)
|
||||
}
|
||||
|
||||
if err := writeReports(summary, payloadAnalysis, *reportDir); err != nil {
|
||||
log.Fatalf("failed to write reports: %v", err)
|
||||
}
|
||||
|
||||
printSummary(summary, *reportDir)
|
||||
if payloadAnalysis != nil {
|
||||
printPayloadAnalysis(*payloadAnalysis, *reportDir)
|
||||
}
|
||||
}
|
||||
|
||||
func loadVectors(path string) (simulationVectors, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return simulationVectors{}, err
|
||||
}
|
||||
|
||||
var dataset simulationVectors
|
||||
if err := json.Unmarshal(raw, &dataset); err != nil {
|
||||
return simulationVectors{}, err
|
||||
}
|
||||
return dataset, nil
|
||||
}
|
||||
|
||||
type accumulator struct {
|
||||
executed int
|
||||
successful int
|
||||
grossWei *big.Int
|
||||
gasWei *big.Int
|
||||
netWei *big.Int
|
||||
}
|
||||
|
||||
func newAccumulator() *accumulator {
|
||||
return &accumulator{
|
||||
grossWei: big.NewInt(0),
|
||||
gasWei: big.NewInt(0),
|
||||
netWei: big.NewInt(0),
|
||||
}
|
||||
}
|
||||
|
||||
func computeSummary(vectorPath string, dataset simulationVectors) (simulationSummary, error) {
|
||||
totalOpportunities := len(dataset.Opportunities)
|
||||
var executed, successful int
|
||||
var grossWei, gasWei, netWei big.Int
|
||||
|
||||
exchangeStats := make(map[string]*accumulator)
|
||||
skipReasonCounts := make(map[string]int)
|
||||
|
||||
for _, opp := range dataset.Opportunities {
|
||||
exchangeKey := strings.ToLower(opp.Exchange)
|
||||
if exchangeKey == "" {
|
||||
exchangeKey = "unknown"
|
||||
}
|
||||
if _, ok := exchangeStats[exchangeKey]; !ok {
|
||||
exchangeStats[exchangeKey] = newAccumulator()
|
||||
}
|
||||
|
||||
if !opp.Executed {
|
||||
reason := opp.SkipReason
|
||||
if reason == "" {
|
||||
reason = "unspecified"
|
||||
}
|
||||
skipReasonCounts[reason]++
|
||||
continue
|
||||
}
|
||||
|
||||
executed++
|
||||
acc := exchangeStats[exchangeKey]
|
||||
acc.executed++
|
||||
|
||||
expected := parseBigInt(opp.ExpectedProfitWei)
|
||||
realized := parseBigInt(opp.RealizedProfitWei)
|
||||
if opp.RealizedProfitWei == "" {
|
||||
realized = expected
|
||||
}
|
||||
|
||||
if opp.SlippageLossWei != "" {
|
||||
realized.Sub(realized, parseBigInt(opp.SlippageLossWei))
|
||||
if realized.Sign() < 0 {
|
||||
realized = big.NewInt(0)
|
||||
}
|
||||
}
|
||||
|
||||
gas := parseBigInt(opp.GasCostWei)
|
||||
|
||||
grossWei.Add(&grossWei, realized)
|
||||
gasWei.Add(&gasWei, gas)
|
||||
|
||||
net := new(big.Int).Sub(realized, gas)
|
||||
netWei.Add(&netWei, net)
|
||||
|
||||
acc.grossWei.Add(acc.grossWei, realized)
|
||||
acc.gasWei.Add(acc.gasWei, gas)
|
||||
acc.netWei.Add(acc.netWei, net)
|
||||
|
||||
if net.Sign() > 0 {
|
||||
successful++
|
||||
acc.successful++
|
||||
}
|
||||
}
|
||||
|
||||
failed := executed - successful
|
||||
conversionRate := safeRatio(float64(executed), float64(totalOpportunities))
|
||||
hitRate := safeRatio(float64(successful), float64(executed))
|
||||
|
||||
avgProfit := big.NewRat(0, 1)
|
||||
if executed > 0 {
|
||||
avgProfit.SetFrac(&netWei, big.NewInt(int64(executed)))
|
||||
}
|
||||
|
||||
avgGas := big.NewRat(0, 1)
|
||||
if executed > 0 {
|
||||
avgGas.SetFrac(&gasWei, big.NewInt(int64(executed)))
|
||||
}
|
||||
|
||||
profitFactor := 0.0
|
||||
if gasWei.Sign() > 0 {
|
||||
gasRat := new(big.Rat).SetInt(&gasWei)
|
||||
netRat := new(big.Rat).SetInt(&netWei)
|
||||
profitFactor, _ = new(big.Rat).Quo(netRat, gasRat).Float64()
|
||||
}
|
||||
|
||||
breakdown := make([]exchangeBreakdown, 0, len(exchangeStats))
|
||||
for name, acc := range exchangeStats {
|
||||
if acc.executed == 0 {
|
||||
continue
|
||||
}
|
||||
breakdown = append(breakdown, exchangeBreakdown{
|
||||
Exchange: name,
|
||||
Executed: acc.executed,
|
||||
Successful: acc.successful,
|
||||
HitRate: safeRatio(float64(acc.successful), float64(acc.executed)),
|
||||
GrossProfitETH: weiToEthString(acc.grossWei),
|
||||
NetProfitETH: weiToEthString(acc.netWei),
|
||||
GasCostETH: weiToEthString(acc.gasWei),
|
||||
})
|
||||
}
|
||||
sort.Slice(breakdown, func(i, j int) bool {
|
||||
return breakdown[i].Exchange < breakdown[j].Exchange
|
||||
})
|
||||
|
||||
skipList := make([]skipReason, 0, len(skipReasonCounts))
|
||||
for reason, count := range skipReasonCounts {
|
||||
skipList = append(skipList, skipReason{Reason: reason, Count: count})
|
||||
}
|
||||
sort.Slice(skipList, func(i, j int) bool {
|
||||
return skipList[i].Count > skipList[j].Count
|
||||
})
|
||||
|
||||
summary := simulationSummary{
|
||||
GeneratedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
VectorPath: vectorPath,
|
||||
Network: dataset.Metadata.Network,
|
||||
Window: dataset.Metadata.Window,
|
||||
Sources: dataset.Metadata.Sources,
|
||||
Attempts: totalOpportunities,
|
||||
Executed: executed,
|
||||
ConversionRate: conversionRate,
|
||||
Successful: successful,
|
||||
Failed: failed,
|
||||
HitRate: hitRate,
|
||||
GrossProfitETH: weiToEthString(&grossWei),
|
||||
GasCostETH: weiToEthString(&gasWei),
|
||||
NetProfitETH: weiToEthString(&netWei),
|
||||
AverageProfitETH: weiRatToEthString(avgProfit),
|
||||
AverageGasCostETH: weiRatToEthString(avgGas),
|
||||
ProfitFactor: profitFactor,
|
||||
ExchangeBreakdown: breakdown,
|
||||
SkipReasons: skipList,
|
||||
}
|
||||
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func analyzePayloads(dir string) (payloadAnalysisReport, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return payloadAnalysisReport{}, fmt.Errorf("read payload directory: %w", err)
|
||||
}
|
||||
|
||||
report := payloadAnalysisReport{
|
||||
GeneratedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
Directory: dir,
|
||||
}
|
||||
|
||||
protocolCounts := make(map[string]int)
|
||||
contractCounts := make(map[string]int)
|
||||
functionCounts := make(map[string]int)
|
||||
|
||||
var (
|
||||
totalInputBytes int
|
||||
earliest time.Time
|
||||
latest time.Time
|
||||
haveTimestamp bool
|
||||
samples []string
|
||||
)
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
|
||||
continue
|
||||
}
|
||||
|
||||
payloadPath := filepath.Join(dir, entry.Name())
|
||||
raw, err := os.ReadFile(payloadPath)
|
||||
if err != nil {
|
||||
return payloadAnalysisReport{}, fmt.Errorf("read payload %s: %w", payloadPath, err)
|
||||
}
|
||||
|
||||
var payload payloadEntry
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return payloadAnalysisReport{}, fmt.Errorf("decode payload %s: %w", payloadPath, err)
|
||||
}
|
||||
|
||||
report.FileCount++
|
||||
|
||||
timestampToken := strings.TrimSuffix(entry.Name(), filepath.Ext(entry.Name()))
|
||||
if idx := strings.Index(timestampToken, "_"); idx != -1 {
|
||||
timestampToken = timestampToken[:idx]
|
||||
}
|
||||
if ts, err := parseCaptureTimestamp(timestampToken); err == nil {
|
||||
if !haveTimestamp || ts.Before(earliest) {
|
||||
earliest = ts
|
||||
}
|
||||
if !haveTimestamp || ts.After(latest) {
|
||||
latest = ts
|
||||
}
|
||||
haveTimestamp = true
|
||||
}
|
||||
|
||||
protocol := strings.TrimSpace(payload.Protocol)
|
||||
if protocol == "" {
|
||||
protocol = "unknown"
|
||||
}
|
||||
protocolCounts[protocol]++
|
||||
|
||||
contract := strings.TrimSpace(payload.Contract)
|
||||
if contract == "" {
|
||||
contract = "unknown"
|
||||
}
|
||||
contractCounts[contract]++
|
||||
|
||||
function := strings.TrimSpace(payload.Function)
|
||||
if function == "" {
|
||||
function = "unknown"
|
||||
}
|
||||
functionCounts[function]++
|
||||
|
||||
if payload.BlockNumber == "" {
|
||||
report.MissingBlockNumber++
|
||||
}
|
||||
if payload.Recipient == "" {
|
||||
report.MissingRecipient++
|
||||
}
|
||||
value := strings.TrimSpace(payload.Value)
|
||||
if value != "" && value != "0" && value != "0x0" {
|
||||
report.NonZeroValueCount++
|
||||
}
|
||||
|
||||
totalInputBytes += estimateHexBytes(payload.InputData)
|
||||
|
||||
if payload.Hash != "" && len(samples) < 5 {
|
||||
samples = append(samples, payload.Hash)
|
||||
}
|
||||
}
|
||||
|
||||
if report.FileCount == 0 {
|
||||
return payloadAnalysisReport{}, fmt.Errorf("no payload JSON files found in %s", dir)
|
||||
}
|
||||
|
||||
report.Protocols = buildNamedCounts(protocolCounts, report.FileCount)
|
||||
report.Contracts = buildNamedCounts(contractCounts, report.FileCount)
|
||||
report.Functions = buildNamedCounts(functionCounts, report.FileCount)
|
||||
|
||||
if haveTimestamp {
|
||||
report.TimeRange = payloadTimeRange{
|
||||
Earliest: earliest.UTC().Format(time.RFC3339),
|
||||
Latest: latest.UTC().Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
report.AverageInputBytes = math.Round((float64(totalInputBytes)/float64(report.FileCount))*100) / 100
|
||||
report.SampleTransactionHashes = samples
|
||||
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func parseCaptureTimestamp(token string) (time.Time, error) {
|
||||
layouts := []string{
|
||||
"20060102T150405.000Z",
|
||||
"20060102T150405Z",
|
||||
}
|
||||
for _, layout := range layouts {
|
||||
if ts, err := time.Parse(layout, token); err == nil {
|
||||
return ts, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("unrecognised timestamp token %q", token)
|
||||
}
|
||||
|
||||
func buildNamedCounts(counts map[string]int, total int) []namedCount {
|
||||
items := make([]namedCount, 0, len(counts))
|
||||
for name, count := range counts {
|
||||
percentage := 0.0
|
||||
if total > 0 {
|
||||
percentage = (float64(count) / float64(total)) * 100
|
||||
percentage = math.Round(percentage*100) / 100 // 2 decimal places
|
||||
}
|
||||
items = append(items, namedCount{
|
||||
Name: name,
|
||||
Count: count,
|
||||
Percentage: percentage,
|
||||
})
|
||||
}
|
||||
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if items[i].Count == items[j].Count {
|
||||
return items[i].Name < items[j].Name
|
||||
}
|
||||
return items[i].Count > items[j].Count
|
||||
})
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
func parseBigInt(value string) *big.Int {
|
||||
if value == "" {
|
||||
return big.NewInt(0)
|
||||
}
|
||||
if strings.HasPrefix(value, "0x") {
|
||||
val := new(big.Int)
|
||||
val.SetString(value[2:], 16)
|
||||
return val
|
||||
}
|
||||
val := new(big.Int)
|
||||
val.SetString(value, 10)
|
||||
return val
|
||||
}
|
||||
|
||||
func safeRatio(num, den float64) float64 {
|
||||
if den == 0 {
|
||||
return 0
|
||||
}
|
||||
return num / den
|
||||
}
|
||||
|
||||
func weiToEthString(val *big.Int) string {
|
||||
if val == nil {
|
||||
return "0.000000"
|
||||
}
|
||||
rat := new(big.Rat).SetInt(val)
|
||||
eth := new(big.Rat).Mul(rat, weiToEthScale)
|
||||
return eth.FloatString(6)
|
||||
}
|
||||
|
||||
func weiRatToEthString(rat *big.Rat) string {
|
||||
if rat.Sign() == 0 {
|
||||
return "0"
|
||||
}
|
||||
eth := new(big.Rat).Mul(rat, weiToEthScale)
|
||||
return eth.FloatString(6)
|
||||
}
|
||||
|
||||
func writeReports(summary simulationSummary, payload *payloadAnalysisReport, reportDir string) error {
|
||||
if err := os.MkdirAll(reportDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := writeSimulationReports(summary, reportDir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if payload != nil {
|
||||
if err := writePayloadReports(*payload, reportDir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeSimulationReports(summary simulationSummary, reportDir string) error {
|
||||
if err := os.MkdirAll(reportDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
jsonPath := filepath.Join(reportDir, "summary.json")
|
||||
jsonBytes, err := json.MarshalIndent(summary, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(jsonPath, jsonBytes, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
markdownPath := filepath.Join(reportDir, "summary.md")
|
||||
if err := os.WriteFile(markdownPath, []byte(buildSimulationMarkdown(summary)), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writePayloadReports(analysis payloadAnalysisReport, reportDir string) error {
|
||||
jsonPath := filepath.Join(reportDir, "payload_analysis.json")
|
||||
jsonBytes, err := json.MarshalIndent(analysis, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(jsonPath, jsonBytes, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mdPath := filepath.Join(reportDir, "payload_analysis.md")
|
||||
if err := os.WriteFile(mdPath, []byte(buildPayloadMarkdown(analysis)), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildSimulationMarkdown(summary simulationSummary) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("# Profitability Simulation Report\n\n")
|
||||
b.WriteString(fmt.Sprintf("- Generated at: %s\n", summary.GeneratedAt))
|
||||
b.WriteString(fmt.Sprintf("- Vector source: `%s`\n", summary.VectorPath))
|
||||
if summary.Network != "" {
|
||||
b.WriteString(fmt.Sprintf("- Network: **%s**\n", summary.Network))
|
||||
}
|
||||
if summary.Window != "" {
|
||||
b.WriteString(fmt.Sprintf("- Window: %s\n", summary.Window))
|
||||
}
|
||||
if len(summary.Sources) > 0 {
|
||||
b.WriteString(fmt.Sprintf("- Exchanges: %s\n", strings.Join(summary.Sources, ", ")))
|
||||
}
|
||||
|
||||
b.WriteString("\n## Summary\n\n")
|
||||
b.WriteString(fmt.Sprintf("- Opportunities analysed: **%d**\n", summary.Attempts))
|
||||
b.WriteString(fmt.Sprintf("- Executed: **%d** (conversion %.1f%%)\n", summary.Executed, summary.ConversionRate*100))
|
||||
b.WriteString(fmt.Sprintf("- Successes: **%d** / %d (hit rate %.1f%%)\n", summary.Successful, summary.Executed, summary.HitRate*100))
|
||||
b.WriteString(fmt.Sprintf("- Gross profit: **%s ETH**\n", summary.GrossProfitETH))
|
||||
b.WriteString(fmt.Sprintf("- Gas spent: **%s ETH**\n", summary.GasCostETH))
|
||||
b.WriteString(fmt.Sprintf("- Net profit after gas: **%s ETH**\n", summary.NetProfitETH))
|
||||
b.WriteString(fmt.Sprintf("- Avg profit per trade: **%s ETH**\n", summary.AverageProfitETH))
|
||||
b.WriteString(fmt.Sprintf("- Avg gas cost per trade: **%s ETH**\n", summary.AverageGasCostETH))
|
||||
b.WriteString(fmt.Sprintf("- Profit factor (net/gas): **%.2f**\n", summary.ProfitFactor))
|
||||
|
||||
if len(summary.ExchangeBreakdown) > 0 {
|
||||
b.WriteString("\n## Exchange Breakdown\n\n")
|
||||
b.WriteString("| Exchange | Executed | Success | Hit Rate | Gross Profit (ETH) | Gas (ETH) | Net Profit (ETH) |\n")
|
||||
b.WriteString("| --- | ---:| ---:| ---:| ---:| ---:| ---:|\n")
|
||||
for _, ex := range summary.ExchangeBreakdown {
|
||||
b.WriteString(fmt.Sprintf("| %s | %d | %d | %.1f%% | %s | %s | %s |\n",
|
||||
ex.Exchange, ex.Executed, ex.Successful, ex.HitRate*100, ex.GrossProfitETH, ex.GasCostETH, ex.NetProfitETH))
|
||||
}
|
||||
}
|
||||
|
||||
if len(summary.SkipReasons) > 0 {
|
||||
b.WriteString("\n## Skip Reasons\n\n")
|
||||
for _, reason := range summary.SkipReasons {
|
||||
b.WriteString(fmt.Sprintf("- %s: %d\n", reason.Reason, reason.Count))
|
||||
}
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func buildPayloadMarkdown(analysis payloadAnalysisReport) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("# Payload Capture Analysis\n\n")
|
||||
b.WriteString(fmt.Sprintf("- Generated at: %s\n", analysis.GeneratedAt))
|
||||
b.WriteString(fmt.Sprintf("- Source directory: `%s`\n", analysis.Directory))
|
||||
b.WriteString(fmt.Sprintf("- Files analysed: **%d**\n", analysis.FileCount))
|
||||
if analysis.TimeRange.Earliest != "" || analysis.TimeRange.Latest != "" {
|
||||
b.WriteString(fmt.Sprintf("- Capture window: %s → %s\n", analysis.TimeRange.Earliest, analysis.TimeRange.Latest))
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("- Average calldata size: %.2f bytes\n", analysis.AverageInputBytes))
|
||||
b.WriteString(fmt.Sprintf("- Payloads with non-zero value: %d\n", analysis.NonZeroValueCount))
|
||||
b.WriteString(fmt.Sprintf("- Missing block numbers: %d\n", analysis.MissingBlockNumber))
|
||||
b.WriteString(fmt.Sprintf("- Missing recipients: %d\n", analysis.MissingRecipient))
|
||||
|
||||
if len(analysis.Protocols) > 0 {
|
||||
b.WriteString("\n## Protocol Distribution\n\n")
|
||||
b.WriteString("| Protocol | Count | Share |\n")
|
||||
b.WriteString("| --- | ---:| ---:|\n")
|
||||
for _, item := range analysis.Protocols {
|
||||
b.WriteString(fmt.Sprintf("| %s | %d | %.2f%% |\n", item.Name, item.Count, item.Percentage))
|
||||
}
|
||||
}
|
||||
|
||||
if len(analysis.Contracts) > 0 {
|
||||
b.WriteString("\n## Contract Names\n\n")
|
||||
b.WriteString("| Contract | Count | Share |\n")
|
||||
b.WriteString("| --- | ---:| ---:|\n")
|
||||
for _, item := range analysis.Contracts {
|
||||
b.WriteString(fmt.Sprintf("| %s | %d | %.2f%% |\n", item.Name, item.Count, item.Percentage))
|
||||
}
|
||||
}
|
||||
|
||||
if len(analysis.Functions) > 0 {
|
||||
b.WriteString("\n## Function Signatures\n\n")
|
||||
b.WriteString("| Function | Count | Share |\n")
|
||||
b.WriteString("| --- | ---:| ---:|\n")
|
||||
for _, item := range analysis.Functions {
|
||||
b.WriteString(fmt.Sprintf("| %s | %d | %.2f%% |\n", item.Name, item.Count, item.Percentage))
|
||||
}
|
||||
}
|
||||
|
||||
if len(analysis.SampleTransactionHashes) > 0 {
|
||||
b.WriteString("\n## Sample Transactions\n\n")
|
||||
for _, hash := range analysis.SampleTransactionHashes {
|
||||
b.WriteString(fmt.Sprintf("- `%s`\n", hash))
|
||||
}
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func printSummary(summary simulationSummary, reportDir string) {
|
||||
fmt.Println("Profitability Simulation Summary")
|
||||
fmt.Println("================================")
|
||||
fmt.Printf("Opportunities: %d\n", summary.Attempts)
|
||||
fmt.Printf("Executed: %d (conversion %.1f%%)\n", summary.Executed, summary.ConversionRate*100)
|
||||
fmt.Printf("Hit Rate: %.1f%% (%d successes, %d failures)\n", summary.HitRate*100, summary.Successful, summary.Failed)
|
||||
fmt.Printf("Gross Profit: %s ETH\n", summary.GrossProfitETH)
|
||||
fmt.Printf("Gas Spent: %s ETH\n", summary.GasCostETH)
|
||||
fmt.Printf("Net Profit: %s ETH\n", summary.NetProfitETH)
|
||||
fmt.Printf("Average Profit/Trade: %s ETH\n", summary.AverageProfitETH)
|
||||
fmt.Printf("Average Gas/Trade: %s ETH\n", summary.AverageGasCostETH)
|
||||
fmt.Printf("Profit Factor: %.2f\n", summary.ProfitFactor)
|
||||
if len(summary.ExchangeBreakdown) > 0 {
|
||||
fmt.Println("\nPer Exchange:")
|
||||
for _, ex := range summary.ExchangeBreakdown {
|
||||
fmt.Printf("- %s: executed %d, hit rate %.1f%%, net %s ETH\n", ex.Exchange, ex.Executed, ex.HitRate*100, ex.NetProfitETH)
|
||||
}
|
||||
}
|
||||
fmt.Println("\nReports written to", reportDir)
|
||||
}
|
||||
|
||||
func printPayloadAnalysis(analysis payloadAnalysisReport, reportDir string) {
|
||||
fmt.Println("\nPayload Capture Analysis")
|
||||
fmt.Println("========================")
|
||||
fmt.Printf("Files analysed: %d\n", analysis.FileCount)
|
||||
if analysis.TimeRange.Earliest != "" || analysis.TimeRange.Latest != "" {
|
||||
fmt.Printf("Capture window: %s → %s\n", analysis.TimeRange.Earliest, analysis.TimeRange.Latest)
|
||||
}
|
||||
fmt.Printf("Average calldata size: %.2f bytes\n", analysis.AverageInputBytes)
|
||||
fmt.Printf("Payloads with non-zero value: %d\n", analysis.NonZeroValueCount)
|
||||
fmt.Printf("Missing block numbers: %d\n", analysis.MissingBlockNumber)
|
||||
fmt.Printf("Missing recipients: %d\n", analysis.MissingRecipient)
|
||||
|
||||
if len(analysis.Protocols) > 0 {
|
||||
fmt.Println("\nTop Protocols:")
|
||||
for _, item := range analysis.Protocols {
|
||||
fmt.Printf("- %s: %d (%.2f%%)\n", item.Name, item.Count, item.Percentage)
|
||||
}
|
||||
}
|
||||
|
||||
if len(analysis.SampleTransactionHashes) > 0 {
|
||||
fmt.Println("\nSample transaction hashes:")
|
||||
for _, hash := range analysis.SampleTransactionHashes {
|
||||
fmt.Printf("- %s\n", hash)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("\nPayload analysis saved as payload_analysis.json and payload_analysis.md in %s\n", reportDir)
|
||||
}
|
||||
|
||||
func estimateHexBytes(value string) int {
|
||||
if value == "" {
|
||||
return 0
|
||||
}
|
||||
trimmed := strings.TrimSpace(value)
|
||||
trimmed = strings.TrimPrefix(trimmed, "0x")
|
||||
if len(trimmed) == 0 {
|
||||
return 0
|
||||
}
|
||||
if len(trimmed)%2 != 0 {
|
||||
trimmed = "0" + trimmed
|
||||
}
|
||||
return len(trimmed) / 2
|
||||
}
|
||||
46
orig/tools/simulation/main_test.go
Normal file
46
orig/tools/simulation/main_test.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestComputeSummaryDefaultVectors(t *testing.T) {
|
||||
dataset, err := loadVectors("vectors/default.json")
|
||||
if err != nil {
|
||||
t.Fatalf("loadVectors: %v", err)
|
||||
}
|
||||
|
||||
summary, err := computeSummary("vectors/default.json", dataset)
|
||||
if err != nil {
|
||||
t.Fatalf("computeSummary: %v", err)
|
||||
}
|
||||
|
||||
if summary.Attempts != 5 {
|
||||
t.Fatalf("expected 5 attempts, got %d", summary.Attempts)
|
||||
}
|
||||
if summary.Executed != 4 {
|
||||
t.Fatalf("expected 4 executed, got %d", summary.Executed)
|
||||
}
|
||||
if summary.Successful != 3 {
|
||||
t.Fatalf("expected 3 successful, got %d", summary.Successful)
|
||||
}
|
||||
if summary.Failed != 1 {
|
||||
t.Fatalf("expected 1 failed, got %d", summary.Failed)
|
||||
}
|
||||
if summary.GrossProfitETH != "0.101000" {
|
||||
t.Fatalf("gross profit mismatch: %s", summary.GrossProfitETH)
|
||||
}
|
||||
if summary.GasCostETH != "0.013700" {
|
||||
t.Fatalf("gas cost mismatch: %s", summary.GasCostETH)
|
||||
}
|
||||
if summary.NetProfitETH != "0.087300" {
|
||||
t.Fatalf("net profit mismatch: %s", summary.NetProfitETH)
|
||||
}
|
||||
if summary.AverageProfitETH != "0.021825" {
|
||||
t.Fatalf("avg profit mismatch: %s", summary.AverageProfitETH)
|
||||
}
|
||||
if summary.AverageGasCostETH != "0.003425" {
|
||||
t.Fatalf("avg gas mismatch: %s", summary.AverageGasCostETH)
|
||||
}
|
||||
if len(summary.ExchangeBreakdown) != 3 {
|
||||
t.Fatalf("expected 3 exchanges, got %d", len(summary.ExchangeBreakdown))
|
||||
}
|
||||
}
|
||||
56
orig/tools/simulation/vectors/default.json
Normal file
56
orig/tools/simulation/vectors/default.json
Normal file
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"metadata": {
|
||||
"network": "arbitrum-one",
|
||||
"window": "2024-09-15T00:00:00Z/2024-09-15T01:00:00Z",
|
||||
"sources": ["uniswap-v3", "camelot", "sushiswap"],
|
||||
"notes": "Synthetic sample covering three exchanges across one-hour slice"
|
||||
},
|
||||
"opportunities": [
|
||||
{
|
||||
"id": "arb-001",
|
||||
"timestamp": "2024-09-15T00:05:12Z",
|
||||
"exchange": "uniswap-v3",
|
||||
"expected_profit_wei": "42000000000000000",
|
||||
"gas_cost_wei": "3100000000000000",
|
||||
"executed": true,
|
||||
"realized_profit_wei": "39800000000000000"
|
||||
},
|
||||
{
|
||||
"id": "arb-002",
|
||||
"timestamp": "2024-09-15T00:17:44Z",
|
||||
"exchange": "camelot",
|
||||
"expected_profit_wei": "28500000000000000",
|
||||
"gas_cost_wei": "2900000000000000",
|
||||
"executed": true,
|
||||
"realized_profit_wei": "12000000000000000"
|
||||
},
|
||||
{
|
||||
"id": "arb-003",
|
||||
"timestamp": "2024-09-15T00:26:09Z",
|
||||
"exchange": "uniswap-v3",
|
||||
"expected_profit_wei": "15000000000000000",
|
||||
"gas_cost_wei": "3500000000000000",
|
||||
"executed": false,
|
||||
"skip_reason": "below_min_profit"
|
||||
},
|
||||
{
|
||||
"id": "arb-004",
|
||||
"timestamp": "2024-09-15T00:38:57Z",
|
||||
"exchange": "sushiswap",
|
||||
"expected_profit_wei": "51000000000000000",
|
||||
"gas_cost_wei": "4700000000000000",
|
||||
"executed": true,
|
||||
"realized_profit_wei": "49200000000000000"
|
||||
},
|
||||
{
|
||||
"id": "arb-005",
|
||||
"timestamp": "2024-09-15T00:52:31Z",
|
||||
"exchange": "camelot",
|
||||
"expected_profit_wei": "19000000000000000",
|
||||
"gas_cost_wei": "3000000000000000",
|
||||
"executed": true,
|
||||
"realized_profit_wei": "0",
|
||||
"slippage_loss_wei": "2100000000000000"
|
||||
}
|
||||
]
|
||||
}
|
||||
151
orig/tools/tests/ci_agent_bridge_test.go
Normal file
151
orig/tools/tests/ci_agent_bridge_test.go
Normal file
@@ -0,0 +1,151 @@
|
||||
// tools/tests/ci_agent_bridge_test.go
|
||||
//
|
||||
// Unit tests for ci-agent-bridge CLI.
|
||||
// Covers patch application, branch reverts, artifact summarization, and podman runner.
|
||||
//
|
||||
// Run with:
|
||||
// go test ./tools/tests -v -race -cover
|
||||
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
// Import the bridge for direct function testing.
|
||||
// Adjust path if your project structure differs.
|
||||
bridge "github.com/fraktal/mev-beta/tools/bridge"
|
||||
)
|
||||
|
||||
// helper: create temporary directory with dummy artifact files
|
||||
func createDummyArtifacts(t *testing.T) string {
|
||||
dir, err := os.MkdirTemp("", "artifacts")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp dir: %v", err)
|
||||
}
|
||||
|
||||
// write 2 dummy files
|
||||
if err := os.WriteFile(filepath.Join(dir, "a.log"), []byte("log-data-123"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "b.txt"), []byte("text-data-456"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func TestSummarizeArtifacts(t *testing.T) {
|
||||
dir := createDummyArtifacts(t)
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
outFile := filepath.Join(dir, "summary.json")
|
||||
cfg := bridge.SummarizeConfig{
|
||||
ArtifactsDir: dir,
|
||||
OutputFile: outFile,
|
||||
}
|
||||
if err := bridge.SummarizeArtifacts(cfg); err != nil {
|
||||
t.Fatalf("summarize failed: %v", err)
|
||||
}
|
||||
|
||||
// verify JSON exists
|
||||
data, err := os.ReadFile(outFile)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read summary.json: %v", err)
|
||||
}
|
||||
|
||||
var parsed bridge.SummarizeResult
|
||||
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||
t.Fatalf("failed to unmarshal json: %v", err)
|
||||
}
|
||||
|
||||
if len(parsed.Files) < 2 {
|
||||
t.Errorf("expected >=2 files, got %d", len(parsed.Files))
|
||||
}
|
||||
if parsed.Timestamp.IsZero() {
|
||||
t.Errorf("expected timestamp set")
|
||||
}
|
||||
|
||||
// verify ZIP archive created
|
||||
if _, err := os.Stat(filepath.Join(dir, "summary.zip")); os.IsNotExist(err) {
|
||||
t.Errorf("expected summary.zip archive, not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyPatch_MissingArgs(t *testing.T) {
|
||||
op := bridge.PatchOperation{}
|
||||
err := bridge.ApplyPatch(op)
|
||||
if err == nil {
|
||||
t.Fatal("expected error when patchfile/branch missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevertBranch_MissingBranch(t *testing.T) {
|
||||
err := bridge.RevertBranch("")
|
||||
if err == nil {
|
||||
t.Fatal("expected error when branch missing")
|
||||
}
|
||||
}
|
||||
|
||||
// Integration-like test with mock podman-compose
|
||||
func TestRunPodmanCompose(t *testing.T) {
|
||||
// simulate podman-compose using echo
|
||||
tmpPath := filepath.Join(os.TempDir(), "podman-compose")
|
||||
if err := os.WriteFile(tmpPath, []byte("#!/bin/sh\necho podman-compose-run"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpPath)
|
||||
|
||||
// put tmpPath at beginning of PATH
|
||||
oldPath := os.Getenv("PATH")
|
||||
os.Setenv("PATH", filepath.Dir(tmpPath)+":"+oldPath)
|
||||
defer os.Setenv("PATH", oldPath)
|
||||
|
||||
err := bridge.RunPodmanCompose()
|
||||
if err != nil {
|
||||
t.Fatalf("expected mock podman-compose to succeed, got err: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestZipDir ensures ZIP creation works standalone
|
||||
func TestZipDir(t *testing.T) {
|
||||
dir := createDummyArtifacts(t)
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
dest := filepath.Join(dir, "out.zip")
|
||||
if err := bridge.ZipDir(dir, dest); err != nil {
|
||||
t.Fatalf("zipdir failed: %v", err)
|
||||
}
|
||||
|
||||
info, err := os.Stat(dest)
|
||||
if err != nil {
|
||||
t.Fatalf("zip file not found: %v", err)
|
||||
}
|
||||
if info.Size() == 0 {
|
||||
t.Errorf("zip file is empty")
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark for artifact summarization performance
|
||||
func BenchmarkSummarizeArtifacts(b *testing.B) {
|
||||
dir := createDummyArtifacts(nil)
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
cfg := bridge.SummarizeConfig{
|
||||
ArtifactsDir: dir,
|
||||
OutputFile: filepath.Join(dir, "summary.json"),
|
||||
}
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := bridge.SummarizeArtifacts(cfg); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Example usage doc test
|
||||
func ExampleSummarizeArtifacts() {
|
||||
// This example is for documentation purposes only and doesn't produce output in tests
|
||||
// because it uses temporary directories with random names.
|
||||
}
|
||||
Reference in New Issue
Block a user