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:
34
orig/.claude/commands/analyze-performance.md
Normal file
34
orig/.claude/commands/analyze-performance.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Analyze Performance
|
||||
|
||||
Perform a comprehensive performance analysis of the MEV bot: $ARGUMENTS
|
||||
|
||||
## Analysis Steps:
|
||||
1. **Memory Profiling**: Check for memory leaks and high allocation patterns
|
||||
2. **CPU Profiling**: Identify CPU bottlenecks and hot paths
|
||||
3. **Goroutine Analysis**: Look for goroutine leaks and blocking operations
|
||||
4. **I/O Performance**: Analyze network and disk I/O patterns
|
||||
5. **Concurrency Issues**: Check for race conditions and lock contention
|
||||
|
||||
## Performance Commands to Run:
|
||||
```bash
|
||||
# Memory profile
|
||||
go tool pprof http://localhost:9090/debug/pprof/heap
|
||||
|
||||
# CPU profile
|
||||
go tool pprof http://localhost:9090/debug/pprof/profile?seconds=30
|
||||
|
||||
# Goroutine analysis
|
||||
go tool pprof http://localhost:9090/debug/pprof/goroutine
|
||||
|
||||
# Enable race detector
|
||||
go run -race ./cmd/mev-bot
|
||||
```
|
||||
|
||||
## Analysis Focus Areas:
|
||||
- Worker pool efficiency in `pkg/market/pipeline.go`
|
||||
- Event parsing performance in `pkg/events/`
|
||||
- Uniswap math calculations in `pkg/uniswap/`
|
||||
- Memory usage in large transaction processing
|
||||
- Rate limiting effectiveness in `internal/ratelimit/`
|
||||
|
||||
Please provide specific performance metrics and recommendations for optimization.
|
||||
271
orig/.claude/commands/audit-go-mev.md
Normal file
271
orig/.claude/commands/audit-go-mev.md
Normal file
@@ -0,0 +1,271 @@
|
||||
# Full Audit Checklist — Go MEV Arbitrage Bot
|
||||
|
||||
> Scope: a production-grade Go service that scans mempool/RPCs, finds arbitrage, constructs & signs transactions, and submits them (e.g., direct RPC, Flashbots bundles). Includes any on-chain smart-contracts the bot depends on (adapters, helpers, custom contracts).
|
||||
|
||||
---
|
||||
|
||||
## 1) Planning & scoping (before running tools)
|
||||
|
||||
* ✅ Identify attack surface: private keys, RPC/WS endpoints, mempool sources, bundle relays (Flashbots), third-party libs, config files.
|
||||
* ✅ Define assets at risk (max ETH / tokens), operational windows, and which chains/nodes (e.g., Arbitrum, Ethereum).
|
||||
* ✅ Create test accounts with funded testnet funds and a forked mainnet environment (Anvil/Hardhat/Foundry) for reproducible tests.
|
||||
|
||||
---
|
||||
|
||||
## 2) Static analysis — Go (SAST / linters / vuln DB)
|
||||
|
||||
Run these to find code smells, insecure patterns, and known vulnerable dependencies:
|
||||
|
||||
* Tools to run: `gosec`, `govulncheck`, `staticcheck`, `golangci-lint`. (gosec and govulncheck are high-value for security.) ([GitHub][1])
|
||||
|
||||
Example commands:
|
||||
|
||||
```bash
|
||||
# gosec
|
||||
gosec ./...
|
||||
|
||||
# govulncheck (requires Go toolchain)
|
||||
govulncheck ./...
|
||||
|
||||
# staticcheck via golangci-lint
|
||||
golangci-lint run
|
||||
```
|
||||
|
||||
What to look for:
|
||||
|
||||
* Use of `crypto/rand` vs `math/rand`, insecure parsing of RPC responses, improper TLS skip verify, hard-coded secrets.
|
||||
* Unsafe use of `sync` primitives, race conditions flagged by go vet/staticcheck patterns.
|
||||
|
||||
---
|
||||
|
||||
## 3) Dynamic analysis & runtime checks — Go
|
||||
|
||||
* Run `go test` with race detector and fuzzing (Go 1.18+ built-in fuzz):
|
||||
|
||||
```bash
|
||||
# race detector
|
||||
go test -race ./...
|
||||
|
||||
# fuzzing (example fuzz target)
|
||||
go test -fuzz=Fuzz -fuzztime=10m ./...
|
||||
```
|
||||
|
||||
* Run integration tests on a mainnet-fork (Anvil/Foundry/Hardhat) so you can simulate chain state and mempool behaviours.
|
||||
* Instrument code with pprof and capture CPU/heap profiles during simulated high-throughput runs.
|
||||
|
||||
What to look for:
|
||||
|
||||
* Race detector failures, panics, deadlocks, goroutine leaks (goroutines that grow unbounded during workload).
|
||||
|
||||
---
|
||||
|
||||
## 4) Go security & dependency checks
|
||||
|
||||
* `govulncheck` (re: vulnerable dependencies). ([Go Packages][2])
|
||||
* Dependency graph: `go list -m all` and search for unmaintained or forked packages.
|
||||
* Check for unsafe cgo or native crypto libraries.
|
||||
|
||||
---
|
||||
|
||||
## 5) Code quality & architecture review checklist
|
||||
|
||||
* Error handling: ensure errors are checked and wrapped (`%w`) not ignored.
|
||||
* Context: all network calls accept `context.Context` with deadlines/timeouts.
|
||||
* Modularization: separate mempool ingestion, strategy logic, transaction builder, and signer.
|
||||
* Testability: core arbitrage logic should be pure functions with injected interfaces for RPCs and time.
|
||||
* Secrets: private keys are never in repo, use a secrets manager (Vault / KMS) or env with restricted perms.
|
||||
|
||||
---
|
||||
|
||||
## 6) Concurrency & rate limiting
|
||||
|
||||
* Ensure tight control over goroutine lifecycle (context cancellation).
|
||||
* Use worker pools for RPCs and bounded channels to avoid OOM.
|
||||
* Rate-limit RPC calls and implement backoff/retry strategies with jitter.
|
||||
|
||||
---
|
||||
|
||||
## 7) Transaction building & signing (critical)
|
||||
|
||||
* Validate chain ID, EIP-155 protection, correct v,r,s values.
|
||||
* Nonce management: centralize nonce manager; handle failed/non-broadcast txs and re-sync nonces from node on error.
|
||||
* Gas estimation/testing: include sanity checks & max gas limits.
|
||||
* Signing: prefer hardware/remote signers (KMS, HSM). If local private keys used, ensure file perms and encryption.
|
||||
* Replay protection: verify chain ID usage and consider EIP-1559 parameterization (maxFeePerGas/maxPriorityFeePerGas).
|
||||
* If using Flashbots, validate bundle assembly and simulator checks (see Flashbots docs). ([Flashbots Docs][3])
|
||||
|
||||
---
|
||||
|
||||
## 8) Smart-contract audit (if you have custom contracts or interact closely)
|
||||
|
||||
Run this toolchain (static + dynamic + fuzz + formal):
|
||||
|
||||
* **Slither** for static analysis.
|
||||
* **Mythril** (symbolic analysis) / **MythX** for additional SAST.
|
||||
* **Foundry (forge)** for unit & fuzz tests — Foundry supports fuzzing & is fast. ([Cyfrin][4])
|
||||
* **Echidna** for property-based fuzzing of invariants. ([0xmacro.com][5])
|
||||
* Consider **Manticore**/**Mythril** for deeper symbolic exploration, and **Certora**/formal approaches for critical invariants (if budget allows). ([Medium][6])
|
||||
|
||||
Example solidity workflow:
|
||||
|
||||
```bash
|
||||
# slither
|
||||
slither .
|
||||
|
||||
# Foundry fuzzing
|
||||
forge test --fuzz
|
||||
|
||||
# Echidna (property-based)
|
||||
echidna-test contracts/ --contract MyContract --config echidna.yaml
|
||||
```
|
||||
|
||||
What to test:
|
||||
|
||||
* Reentrancy, arithmetic over/underflow (if not using SafeMath / solidity ^0.8), access-control checks, unexpected token approvals, unchecked external calls.
|
||||
|
||||
---
|
||||
|
||||
## 9) Fuzzing — exhaustive plan
|
||||
|
||||
**Go fuzzing**
|
||||
|
||||
* Use Go’s native fuzz (`go test -fuzz`) for core libraries (parsers, ABI decoders, bundle builders).
|
||||
* Create fuzz targets focusing on:
|
||||
|
||||
* RPC response parsing (malformed JSON).
|
||||
* ABI decoding and calldata construction.
|
||||
* Signed-transaction bytes parser.
|
||||
* Run for long durations with corpus seeding from real RPC responses.
|
||||
|
||||
**Solidity fuzzing**
|
||||
|
||||
* Use Foundry’s `forge test --fuzz` and Echidna to target invariants (balances, no-negative slippage, token conservation).
|
||||
* Seed fuzzers with historical tx traces & typical call sequences.
|
||||
|
||||
**Orchestration**
|
||||
|
||||
* Run fuzzers in CI but also schedule long runs in a buildkite/GitHub Actions runner or dedicated machine.
|
||||
* Capture crashes/inputs and convert them to reproducible testcases.
|
||||
|
||||
References and how-to guides for solidity fuzzing and Foundry usage. ([Cyfrin][4])
|
||||
|
||||
---
|
||||
|
||||
## 10) Penetration-style tests / adversarial scenarios
|
||||
|
||||
* Mempool-level adversary: inject malformed or opponent transactions, test how bot reacts to reorgs & chain reorganizations.
|
||||
* Time/latency: simulate delayed RPC responses and timeouts.
|
||||
* Partial failures: simulate bundle reverts, tx replaced, or gas price spikes.
|
||||
* Economic tests: simulate price or liquidity slippage, oracle manipulation scenarios.
|
||||
|
||||
---
|
||||
|
||||
## 11) Monitoring, metrics & observability
|
||||
|
||||
* Add structured logs (JSON), trace IDs, and use OpenTelemetry or Prometheus metrics for:
|
||||
|
||||
* latency from detection → tx submission,
|
||||
* success/failure counters,
|
||||
* gas usage per tx,
|
||||
* nonce mismatches.
|
||||
* Add alerts for repeated reorgs, high failure rates, or sudden profit/loss anomalies.
|
||||
* Simulate alerting (PagerDuty/Slack) in staging to ensure operational readiness.
|
||||
|
||||
---
|
||||
|
||||
## 12) CI/CD & reproducible tests
|
||||
|
||||
* Integrate all static and dynamic checks into CI:
|
||||
|
||||
* `gosec`, `govulncheck`, `golangci-lint` → fail CI on new high/critical findings.
|
||||
* Unit tests, fuzzing smoke tests (short), Foundry tests for solidity.
|
||||
* Store fuzzing corpora and reproduce minimized crashing inputs in CI artifacts.
|
||||
|
||||
---
|
||||
|
||||
## 13) Secrets & deployment hardening
|
||||
|
||||
* Never commit private keys or mnemonic in code or config. Use secret manager (AWS KMS / GCP KMS / HashiCorp Vault).
|
||||
* Use least-privilege for node credentials; isolate signer service from other components.
|
||||
* Harden nodes: avoid public shared RPCs for production signing; prefer dedicated provider or local node.
|
||||
|
||||
---
|
||||
|
||||
## 14) Reporting format & remediation plan (what the auditor should deliver)
|
||||
|
||||
* **Executive summary:** risk posture and amount at risk.
|
||||
* **Prioritized findings:** Critical / High / Medium / Low / Informational.
|
||||
|
||||
* For each finding: description, evidence (stack trace, log snippets, test reproducer), impact, exploitability, and line-level references.
|
||||
* **Fix recommendation:** code patch or test to cover the case; include sample code where relevant.
|
||||
* **Re-test plan:** how to validate fixes (unit/regression tests, fuzzing seeds).
|
||||
* **Follow-up:** suggested schedule for re-audit (post-fix) and continuous scanning.
|
||||
|
||||
---
|
||||
|
||||
## 15) Severity guidance (example)
|
||||
|
||||
* **Critical:** fund-loss bug; private key compromised; unsigned tx broadcast leak.
|
||||
* **High:** nonce desync under normal load; reentrancy in helper contract called by bot.
|
||||
* **Medium:** panic on malformed RPC response; unbounded goroutine leak.
|
||||
* **Low:** logging missing request IDs; non-idiomatic error handling.
|
||||
* **Informational:** code style, minor refactors.
|
||||
|
||||
---
|
||||
|
||||
## 16) Example concrete test cases to include
|
||||
|
||||
* RPC returns truncated JSON → does the bot panic or gracefully retry?
|
||||
* Node returns `nonce too low` mid-run → does the bot resync or keep retrying stale nonce?
|
||||
* Simulate mempool reordering and reorg of 2 blocks → does bot detect revert & recover?
|
||||
* Flashbots bundle simulator returns revert on one tx → ensure bot doesn’t double-submit other txs.
|
||||
* ABI-decoder fuzzed input causing unexpected `panic` in Go (fuzzer should find).
|
||||
|
||||
---
|
||||
|
||||
## 17) Example commands / CI snippets (condensed)
|
||||
|
||||
```yaml
|
||||
# .github/workflows/ci.yml (snippets)
|
||||
- name: Lint & Security
|
||||
run: |
|
||||
golangci-lint run ./...
|
||||
gosec ./...
|
||||
govulncheck ./...
|
||||
|
||||
- name: Unit + Race
|
||||
run: go test -race ./...
|
||||
|
||||
- name: Go Fuzz (short)
|
||||
run: go test -run TestFuzz -fuzz=Fuzz -fuzztime=1m ./...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 18) Deliverables checklist for the auditor (what to hand back)
|
||||
|
||||
* Full report (PDF/Markdown) with prioritized findings & diffs/patches.
|
||||
* Repro scripts for each failing case (docker-compose or Foundry/Anvil fork commands).
|
||||
* Fuzzing corpora and minimized crashing inputs.
|
||||
* CI changes / workflow proposals for enforcement.
|
||||
* Suggested runtime hardening & monitoring dashboard templates.
|
||||
|
||||
---
|
||||
|
||||
## 19) Helpful references & toolset (quick links)
|
||||
|
||||
* `gosec` — Go security scanner. ([GitHub][1])
|
||||
* `govulncheck` — Go vulnerability scanner for dependencies. ([Go Packages][2])
|
||||
* Foundry (`forge`) — fast solidity testing + fuzzing. ([Cyfrin][4])
|
||||
* Echidna — property-based fuzzing for Solidity. ([0xmacro.com][5])
|
||||
* Slither / Mythril — solidity static analysis & symbolic analysis. ([Medium][6])
|
||||
|
||||
---
|
||||
|
||||
## 20) Final notes & recommended audit cadence
|
||||
|
||||
* Run a full audit (code + solidity + fuzzing) before mainnet launch.
|
||||
* Keep continuous scanning (gosec/govulncheck) in CI on every PR.
|
||||
* Schedule quarterly security re-checks + immediate re-audit for any major dependency or logic change.
|
||||
|
||||
---
|
||||
88
orig/.claude/commands/check-implementations.md
Normal file
88
orig/.claude/commands/check-implementations.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# Check Proper Implementations
|
||||
|
||||
We need to ensure we have a database and make a database connection. We need to ensure that we are logging all exchange data (swaps and liquidity) in their own log file. We need to make absolutely sure that we have all the relevant data (router/factory, token0, token1, amounts, fee, etc).
|
||||
|
||||
## Database Implementation
|
||||
|
||||
The market manager includes a comprehensive database adapter that handles persistence of market data:
|
||||
|
||||
### Database Schema
|
||||
- **markets**: Stores core market information (factory_address, pool_address, token0/1 addresses, fee, ticker, protocol)
|
||||
- **market_data**: Stores price and liquidity data with versioning support (sequencer vs on-chain)
|
||||
- **market_events**: Stores parsed events (swaps, liquidity changes) with full details
|
||||
- **arbitrage_opportunities**: Stores detected arbitrage opportunities for analysis
|
||||
|
||||
### Database Features
|
||||
- PostgreSQL schema with proper indexing for performance
|
||||
- Foreign key constraints for data integrity
|
||||
- JSON serialization for complex data structures
|
||||
- Batch operations for efficiency
|
||||
- Connection pooling support
|
||||
|
||||
### Database Adapter Functions
|
||||
- `NewDatabaseAdapter()`: Creates and tests database connection
|
||||
- `InitializeSchema()`: Creates tables and indexes if they don't exist
|
||||
- `SaveMarket()`: Persists market information
|
||||
- `SaveMarketData()`: Stores price/liquidity data with source tracking
|
||||
- `SaveArbitrageOpportunity()`: Records detected opportunities
|
||||
- `GetMarket()`: Retrieves market by key
|
||||
- `GetLatestMarketData()`: Gets most recent market data
|
||||
|
||||
## Logging Implementation
|
||||
|
||||
The logging system uses a multi-file approach with separation of concerns:
|
||||
|
||||
### Specialized Log Files
|
||||
- **Main log**: General application logging
|
||||
- **Opportunities log**: MEV opportunities and arbitrage attempts
|
||||
- **Errors log**: Errors and warnings only
|
||||
- **Performance log**: Performance metrics and RPC calls
|
||||
- **Transactions log**: Detailed transaction analysis
|
||||
|
||||
### Logging Functions
|
||||
- `Opportunity()`: Logs arbitrage opportunities with full details
|
||||
- `Performance()`: Records performance metrics for optimization
|
||||
- `Transaction()`: Logs detailed transaction information
|
||||
- `BlockProcessing()`: Records block processing metrics
|
||||
- `ArbitrageAnalysis()`: Logs arbitrage opportunity analysis
|
||||
- `RPC()`: Records RPC call metrics for endpoint optimization
|
||||
|
||||
### Exchange Data Logging
|
||||
All exchange data is logged with complete information:
|
||||
- Router/factory addresses
|
||||
- Token0 and Token1 addresses
|
||||
- Swap amounts (both tokens)
|
||||
- Pool fees
|
||||
- Transaction hashes
|
||||
- Block numbers
|
||||
- Timestamps
|
||||
|
||||
## Data Collection Verification
|
||||
|
||||
### Market Data
|
||||
- Markets stored with full identification (factory, pool, tokens)
|
||||
- Price and liquidity data with timestamp tracking
|
||||
- Status tracking (possible, confirmed, stale, invalid)
|
||||
- Protocol information (UniswapV2, UniswapV3, etc.)
|
||||
|
||||
### Event Data
|
||||
- Swap events with complete amount information
|
||||
- Liquidity events (add/remove) with token amounts
|
||||
- Transaction hashes and block numbers for verification
|
||||
- Event types for filtering and analysis
|
||||
|
||||
### Arbitrage Data
|
||||
- Path information for multi-hop opportunities
|
||||
- Profit calculations with gas cost estimation
|
||||
- ROI percentages for opportunity ranking
|
||||
- Status tracking (detected, executed, failed)
|
||||
|
||||
## Implementation Status
|
||||
|
||||
✅ Database connection established and tested
|
||||
✅ Database schema implemented with all required tables
|
||||
✅ Market data persistence with versioning support
|
||||
✅ Event data logging with full exchange details
|
||||
✅ Specialized logging for different data types
|
||||
✅ All required exchange data fields captured
|
||||
✅ Proper error handling and connection management
|
||||
43
orig/.claude/commands/debug-issue.md
Normal file
43
orig/.claude/commands/debug-issue.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# Debug Issue
|
||||
|
||||
Debug the following MEV bot issue: $ARGUMENTS
|
||||
|
||||
## Debugging Protocol:
|
||||
1. **Issue Understanding**: Analyze the problem description and expected vs actual behavior
|
||||
2. **Log Analysis**: Examine relevant log files in `logs/` directory
|
||||
3. **Code Investigation**: Review related source code and recent changes
|
||||
4. **Reproduction**: Attempt to reproduce the issue in a controlled environment
|
||||
5. **Root Cause**: Identify the underlying cause and contributing factors
|
||||
|
||||
## Debugging Commands:
|
||||
```bash
|
||||
# Check logs
|
||||
tail -f logs/mev-bot.log
|
||||
|
||||
# Run with debug logging
|
||||
LOG_LEVEL=debug ./mev-bot start
|
||||
|
||||
# Check system resources
|
||||
htop
|
||||
iostat -x 1 5
|
||||
|
||||
# Network connectivity
|
||||
nc -zv arbitrum-mainnet.core.chainstack.com 443
|
||||
|
||||
# Go runtime stats
|
||||
curl http://localhost:9090/debug/vars | jq
|
||||
```
|
||||
|
||||
## Investigation Areas:
|
||||
- **Connection Issues**: RPC endpoint connectivity and WebSocket stability
|
||||
- **Parsing Errors**: Transaction and event parsing failures
|
||||
- **Performance**: High CPU/memory usage or processing delays
|
||||
- **Concurrency**: Race conditions or deadlocks
|
||||
- **Configuration**: Environment variables and configuration issues
|
||||
|
||||
## Output Requirements:
|
||||
- Clear problem identification
|
||||
- Step-by-step reproduction instructions
|
||||
- Root cause analysis
|
||||
- Proposed solution with implementation steps
|
||||
- Test plan to verify the fix
|
||||
34
orig/.claude/commands/implement-algorithm.md
Normal file
34
orig/.claude/commands/implement-algorithm.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Implement Mathematical Algorithm
|
||||
|
||||
Implement the following mathematical algorithm for the MEV bot: $ARGUMENTS
|
||||
|
||||
## Implementation Framework:
|
||||
1. **Requirements Analysis**: Break down the mathematical requirements and precision needs
|
||||
2. **Formula Implementation**: Convert mathematical formulas to precise Go code
|
||||
3. **Precision Handling**: Use appropriate data types (uint256, big.Int) for calculations
|
||||
4. **Edge Case Handling**: Consider boundary conditions and error scenarios
|
||||
5. **Testing**: Create comprehensive tests including property-based tests
|
||||
6. **Optimization**: Optimize for performance while maintaining precision
|
||||
|
||||
## Implementation Standards:
|
||||
- **Numerical Precision**: Use github.com/holiman/uint256 for precise uint256 arithmetic
|
||||
- **Error Handling**: Implement robust error handling with clear error messages
|
||||
- **Documentation**: Document all mathematical formulas and implementation decisions
|
||||
- **Testing**: Achieve >95% test coverage with property-based tests for mathematical functions
|
||||
- **Performance**: Consider performance implications and benchmark critical paths
|
||||
|
||||
## File Organization:
|
||||
- **Core Logic**: Place in appropriate `pkg/uniswap/` or `pkg/math/` subdirectory
|
||||
- **Tests**: Co-locate with source files (`*_test.go`)
|
||||
- **Documentation**: Inline comments explaining mathematical formulas
|
||||
|
||||
## Integration Points:
|
||||
- **Uniswap Pricing**: Integrate with `pkg/uniswap/` for pricing calculations
|
||||
- **Market Analysis**: Connect to `pkg/market/` for market data processing
|
||||
- **Precision Libraries**: Use `github.com/holiman/uint256` for uint256 arithmetic
|
||||
|
||||
## Deliverables:
|
||||
- Working implementation with comprehensive tests
|
||||
- Documentation of mathematical formulas and implementation approach
|
||||
- Performance benchmarks for critical functions
|
||||
- Edge case handling and error scenarios
|
||||
38
orig/.claude/commands/implement-feature.md
Normal file
38
orig/.claude/commands/implement-feature.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Implement Feature
|
||||
|
||||
Implement the following feature for the MEV bot: $ARGUMENTS
|
||||
|
||||
## Implementation Framework:
|
||||
1. **Requirements Analysis**: Break down the feature requirements and acceptance criteria
|
||||
2. **Architecture Design**: Design the solution following existing patterns
|
||||
3. **Interface Design**: Define clean interfaces between components
|
||||
4. **Implementation**: Write the code following Go best practices
|
||||
5. **Testing**: Create comprehensive unit and integration tests
|
||||
6. **Documentation**: Update relevant documentation and examples
|
||||
|
||||
## Implementation Standards:
|
||||
- **Code Quality**: Follow Go conventions and project coding standards
|
||||
- **Error Handling**: Implement robust error handling with context
|
||||
- **Logging**: Add appropriate logging with structured fields
|
||||
- **Testing**: Achieve >90% test coverage
|
||||
- **Performance**: Consider performance implications and add metrics
|
||||
- **Security**: Validate all inputs and handle edge cases
|
||||
|
||||
## File Organization:
|
||||
- **Core Logic**: Place in appropriate `pkg/` subdirectory
|
||||
- **Configuration**: Add to `internal/config/` if needed
|
||||
- **Tests**: Co-locate with source files (`*_test.go`)
|
||||
- **Documentation**: Update `docs/` and inline comments
|
||||
|
||||
## Integration Points:
|
||||
- **Event System**: Integrate with `pkg/events/` for transaction processing
|
||||
- **Market Pipeline**: Connect to `pkg/market/pipeline.go` for processing
|
||||
- **Monitoring**: Add metrics and health checks
|
||||
- **Configuration**: Add necessary environment variables
|
||||
|
||||
## Deliverables:
|
||||
- Working implementation with tests
|
||||
- Updated documentation
|
||||
- Configuration updates
|
||||
- Performance benchmarks if applicable
|
||||
- Migration guide for existing deployments
|
||||
65
orig/.claude/commands/optimize-math.md
Normal file
65
orig/.claude/commands/optimize-math.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# Optimize Mathematical Performance
|
||||
|
||||
Optimize the performance of the following mathematical function in the MEV bot: $ARGUMENTS
|
||||
|
||||
## Performance Optimization Strategy:
|
||||
|
||||
### 1. **Profiling and Measurement**
|
||||
```bash
|
||||
# CPU profiling for mathematical functions
|
||||
go tool pprof http://localhost:9090/debug/pprof/profile?seconds=30
|
||||
|
||||
# Memory profiling for mathematical calculations
|
||||
go tool pprof http://localhost:9090/debug/pprof/heap
|
||||
|
||||
# Benchmark testing for mathematical functions
|
||||
go test -bench=. -benchmem ./pkg/uniswap/...
|
||||
```
|
||||
|
||||
### 2. **Optimization Areas**
|
||||
|
||||
#### **Precision Handling Optimization**
|
||||
- Uint256 arithmetic optimization
|
||||
- Object pooling for frequent calculations
|
||||
- Minimize memory allocations in hot paths
|
||||
- Efficient conversion between data types
|
||||
|
||||
#### **Algorithm Optimization**
|
||||
- Mathematical formula simplification
|
||||
- Lookup table implementation for repeated calculations
|
||||
- Caching strategies for expensive computations
|
||||
- Parallel processing opportunities
|
||||
|
||||
#### **Memory Optimization**
|
||||
- Pre-allocation of slices and buffers
|
||||
- Object pooling for mathematical objects
|
||||
- Minimize garbage collection pressure
|
||||
- Efficient data structure selection
|
||||
|
||||
### 3. **MEV Bot Specific Optimizations**
|
||||
|
||||
#### **Uniswap V3 Pricing Functions**
|
||||
- sqrtPriceX96 to price conversion optimization
|
||||
- Tick calculation performance improvements
|
||||
- Liquidity-based calculation efficiency
|
||||
- Price impact computation optimization
|
||||
|
||||
#### **Arbitrage Calculations**
|
||||
- Profit calculation optimization
|
||||
- Cross-pool comparison performance
|
||||
- Gas estimation accuracy and speed
|
||||
- Multi-hop arbitrage efficiency
|
||||
|
||||
## Implementation Guidelines:
|
||||
- Measure before optimizing (baseline metrics)
|
||||
- Focus on bottlenecks identified through profiling
|
||||
- Maintain mathematical precision while improving performance
|
||||
- Add performance tests for regressions
|
||||
- Document optimization strategies and results
|
||||
|
||||
## Deliverables:
|
||||
- Performance benchmark results (before/after)
|
||||
- Optimized code with maintained precision
|
||||
- Performance monitoring enhancements
|
||||
- Optimization documentation
|
||||
- Regression test suite
|
||||
84
orig/.claude/commands/optimize-performance.md
Normal file
84
orig/.claude/commands/optimize-performance.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# Optimize Performance
|
||||
|
||||
Optimize the performance of the MEV bot in the following area: $ARGUMENTS
|
||||
|
||||
## Performance Optimization Strategy:
|
||||
|
||||
### 1. **Profiling and Measurement**
|
||||
```bash
|
||||
# CPU profiling
|
||||
go tool pprof http://localhost:9090/debug/pprof/profile?seconds=30
|
||||
|
||||
# Memory profiling
|
||||
go tool pprof http://localhost:9090/debug/pprof/heap
|
||||
|
||||
# Trace analysis
|
||||
go tool trace trace.out
|
||||
|
||||
# Benchmark testing
|
||||
go test -bench=. -benchmem ./...
|
||||
```
|
||||
|
||||
### 2. **Optimization Areas**
|
||||
|
||||
#### **Concurrency Optimization**
|
||||
- Worker pool sizing and configuration
|
||||
- Channel buffer optimization
|
||||
- Goroutine pooling and reuse
|
||||
- Lock contention reduction
|
||||
- Context cancellation patterns
|
||||
|
||||
#### **Memory Optimization**
|
||||
- Object pooling for frequent allocations
|
||||
- Buffer reuse patterns
|
||||
- Garbage collection tuning
|
||||
- Memory leak prevention
|
||||
- Slice and map pre-allocation
|
||||
|
||||
#### **I/O Optimization**
|
||||
- Connection pooling for RPC calls
|
||||
- Request batching and pipelining
|
||||
- Caching frequently accessed data
|
||||
- Asynchronous processing patterns
|
||||
- Rate limiting optimization
|
||||
|
||||
#### **Algorithm Optimization**
|
||||
- Uniswap math calculation efficiency
|
||||
- Event parsing performance
|
||||
- Data structure selection
|
||||
- Caching strategies
|
||||
- Indexing improvements
|
||||
|
||||
### 3. **MEV Bot Specific Optimizations**
|
||||
|
||||
#### **Transaction Processing Pipeline**
|
||||
- Parallel transaction processing
|
||||
- Event filtering optimization
|
||||
- Batch processing strategies
|
||||
- Pipeline stage optimization
|
||||
|
||||
#### **Market Analysis**
|
||||
- Price calculation caching
|
||||
- Pool data caching
|
||||
- Historical data indexing
|
||||
- Real-time processing optimization
|
||||
|
||||
#### **Arbitrage Detection**
|
||||
- Opportunity scanning efficiency
|
||||
- Profit calculation optimization
|
||||
- Market impact analysis speed
|
||||
- Cross-DEX comparison performance
|
||||
|
||||
## Implementation Guidelines:
|
||||
- Measure before optimizing (baseline metrics)
|
||||
- Focus on bottlenecks identified through profiling
|
||||
- Maintain code readability and maintainability
|
||||
- Add performance tests for regressions
|
||||
- Document performance characteristics
|
||||
|
||||
## Deliverables:
|
||||
- Performance benchmark results (before/after)
|
||||
- Optimized code with maintained functionality
|
||||
- Performance monitoring enhancements
|
||||
- Optimization documentation
|
||||
- Regression test suite
|
||||
72
orig/.claude/commands/security-audit.md
Normal file
72
orig/.claude/commands/security-audit.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# Security Audit
|
||||
|
||||
Perform a comprehensive security audit of the MEV bot focusing on: $ARGUMENTS
|
||||
|
||||
## Security Audit Checklist:
|
||||
|
||||
### 1. **Code Security Analysis**
|
||||
```bash
|
||||
# Static security analysis
|
||||
gosec ./...
|
||||
|
||||
# Dependency vulnerabilities
|
||||
go list -json -m all | nancy sleuth
|
||||
|
||||
# Secret scanning
|
||||
git-secrets --scan
|
||||
```
|
||||
|
||||
### 2. **Input Validation Review**
|
||||
- Transaction data parsing validation
|
||||
- RPC response validation
|
||||
- Configuration parameter validation
|
||||
- Mathematical overflow/underflow checks
|
||||
- Buffer overflow prevention
|
||||
|
||||
### 3. **Cryptographic Security**
|
||||
- Private key handling and storage
|
||||
- Signature verification processes
|
||||
- Random number generation
|
||||
- Hash function usage
|
||||
- Encryption at rest and in transit
|
||||
|
||||
### 4. **Network Security**
|
||||
- RPC endpoint authentication
|
||||
- TLS/SSL configuration
|
||||
- Rate limiting implementation
|
||||
- DDoS protection mechanisms
|
||||
- WebSocket connection security
|
||||
|
||||
### 5. **Runtime Security**
|
||||
- Memory safety in Go code
|
||||
- Goroutine safety and race conditions
|
||||
- Resource exhaustion protection
|
||||
- Error information disclosure
|
||||
- Logging security (no sensitive data)
|
||||
|
||||
## Specific MEV Bot Security Areas:
|
||||
|
||||
### **Transaction Processing**
|
||||
- Validate all transaction inputs
|
||||
- Prevent transaction replay attacks
|
||||
- Secure handling of swap calculations
|
||||
- Protection against malicious contract calls
|
||||
|
||||
### **Market Data Integrity**
|
||||
- Price feed validation
|
||||
- Oracle manipulation detection
|
||||
- Historical data integrity
|
||||
- Real-time data verification
|
||||
|
||||
### **Financial Security**
|
||||
- Gas estimation accuracy
|
||||
- Slippage protection
|
||||
- Minimum profit validation
|
||||
- MEV protection mechanisms
|
||||
|
||||
## Output Requirements:
|
||||
- Detailed security findings report
|
||||
- Risk assessment (Critical/High/Medium/Low)
|
||||
- Remediation recommendations
|
||||
- Implementation timeline for fixes
|
||||
- Security testing procedures
|
||||
54
orig/.claude/commands/verify-precision.md
Normal file
54
orig/.claude/commands/verify-precision.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# Verify Mathematical Precision
|
||||
|
||||
Verify the precision and correctness of the following mathematical implementation in the MEV bot: $ARGUMENTS
|
||||
|
||||
## Verification Protocol:
|
||||
|
||||
### 1. **Mathematical Correctness Analysis**
|
||||
- Review mathematical formulas against official specifications
|
||||
- Validate implementation against known test cases
|
||||
- Check boundary conditions and edge cases
|
||||
- Verify precision handling for large numbers
|
||||
|
||||
### 2. **Property-Based Testing**
|
||||
```bash
|
||||
# Run property-based tests for mathematical functions
|
||||
go test -v -run=Property ./pkg/uniswap/...
|
||||
|
||||
# Run fuzz tests for mathematical calculations
|
||||
go test -fuzz=Fuzz ./pkg/uniswap/...
|
||||
```
|
||||
|
||||
### 3. **Precision Validation Areas**
|
||||
|
||||
#### **Uniswap V3 Calculations**
|
||||
- sqrtPriceX96 to price conversion accuracy
|
||||
- Tick calculation correctness
|
||||
- Liquidity-based calculation precision
|
||||
- Price impact computation validation
|
||||
|
||||
#### **Financial Calculations**
|
||||
- Profit calculation accuracy
|
||||
- Gas estimation precision
|
||||
- Slippage protection validation
|
||||
- Fee calculation correctness
|
||||
|
||||
### 4. **Comparison Testing**
|
||||
- Compare results with reference implementations
|
||||
- Validate against on-chain data when possible
|
||||
- Cross-check with other DeFi protocol implementations
|
||||
- Benchmark against established mathematical libraries
|
||||
|
||||
## Verification Steps:
|
||||
1. **Static Analysis**: Review code for mathematical correctness
|
||||
2. **Unit Testing**: Verify with known test cases
|
||||
3. **Property Testing**: Test mathematical invariants
|
||||
4. **Fuzz Testing**: Find edge cases with random inputs
|
||||
5. **Comparison Testing**: Validate against reference implementations
|
||||
|
||||
## Output Requirements:
|
||||
- Detailed correctness analysis report
|
||||
- Precision validation results
|
||||
- Edge case identification and handling
|
||||
- Recommendations for improvements
|
||||
- Test suite enhancements
|
||||
38
orig/.claude/scripts/perf-test.sh
Executable file
38
orig/.claude/scripts/perf-test.sh
Executable file
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
|
||||
# perf-test.sh - Run comprehensive performance tests for Claude
|
||||
|
||||
echo "Running comprehensive performance tests for Claude..."
|
||||
|
||||
# Create results directory if it doesn't exist
|
||||
mkdir -p .claude/results
|
||||
|
||||
# Run unit tests
|
||||
echo "Running unit tests..."
|
||||
go test -v ./... | tee .claude/results/unit-tests.log
|
||||
|
||||
# Run integration tests
|
||||
echo "Running integration tests..."
|
||||
go test -v ./test/integration/... | tee .claude/results/integration-tests.log
|
||||
|
||||
# Run benchmarks
|
||||
echo "Running benchmarks..."
|
||||
go test -bench=. -benchmem ./... | tee .claude/results/benchmarks.log
|
||||
|
||||
# Run benchmarks with CPU profiling
|
||||
echo "Running benchmarks with CPU profiling..."
|
||||
go test -bench=. -cpuprofile=.claude/results/cpu.prof ./... | tee .claude/results/cpu-bench.log
|
||||
|
||||
# Run benchmarks with memory profiling
|
||||
echo "Running benchmarks with memory profiling..."
|
||||
go test -bench=. -memprofile=.claude/results/mem.prof ./... | tee .claude/results/mem-bench.log
|
||||
|
||||
# Check for errors
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "All performance tests completed successfully!"
|
||||
echo "Results saved to .claude/results/"
|
||||
else
|
||||
echo "Some performance tests failed!"
|
||||
echo "Check .claude/results/ for details"
|
||||
exit 1
|
||||
fi
|
||||
Reference in New Issue
Block a user