11# Repository Guidelines
22
3- This guide helps contributors deliver changes to ` buildernet-orderflow-proxy-v2 ` safely and predictably.
3+ This guide helps contributors deliver changes to the project safely and predictably.
44
55## Project Structure & Module Organization
66
77### Entry Points & Core Structure
8+
89- The entrypoint binary lives in ` src/main.rs ` and delegates to the library crate in ` src/lib.rs ` .
910- CLI arguments are defined in ` src/cli.rs ` using the ` clap ` crate.
1011- The ` src/runner/ ` module handles application lifecycle and HTTP server setup.
1112
1213### Domain Modules
14+
1315Core domain logic is organized under ` src/ ` :
16+
1417- ** ` ingress/ ` ** : HTTP handlers for three endpoints:
1518 - ` user.rs ` : Public API for bundle/transaction submission
1619 - ` system.rs ` : Internal API for system operations
@@ -34,44 +37,53 @@ Core domain logic is organized under `src/`:
3437- ** ` tasks/ ` ** : Task execution and graceful shutdown coordination
3538
3639### Supporting Code
40+
3741- ** ` src/utils.rs ` ** : Shared helper functions
3842- ** ` benches/ ` ** : Criterion performance benchmarks
3943- ** ` fixtures/ ` ** : SQL schema files for ClickHouse tables
4044- ** ` simulation/ ` ** : Load testing harness with Docker Compose
4145- ** ` tests/ ` ** : Integration tests with reusable fixtures in ` tests/common/ `
4246
4347### Guidelines for New Code
48+
4449- Place new code in the closest domain module and expose it through ` lib.rs ` .
4550- For cross-cutting concerns, consider adding to ` utils.rs ` or creating a new focused module.
4651- Keep modules focused and cohesive; split large modules into submodules when they exceed ~ 500 lines.
52+
4753## Build, Test, and Development Commands
4854
4955### Building
56+
5057- ` cargo build ` compiles the binary with the default dev profile.
5158- ` cargo build --release ` produces an optimized build with LTO enabled.
5259- ` just build-reproducible ` creates a verifiable production build (uses the ` reproducible ` profile).
5360- ` cargo run -- --help ` prints the CLI flags defined in ` src/cli.rs ` and is the fastest smoke-test.
5461
5562### Testing
63+
5664- ` just test ` runs the test suite using nextest (faster parallel test runner).
5765- ` cargo test ` executes unit and integration tests; add ` -- --nocapture ` when debugging async failures.
5866- ` cargo bench ` runs Criterion benchmarks (validation, signature verification, etc.).
5967- Integration tests use ` testcontainers ` for ClickHouse and require Docker to be running.
6068
6169### Code Quality
70+
6271- ` just fmt ` or ` cargo +nightly fmt --all ` applies formatting rules from ` rustfmt.toml ` .
6372- ` just clippy ` or ` cargo clippy --all-targets --all-features -- -D warnings ` enforces lints.
6473- All linting configuration lives in ` Cargo.toml ` under ` [lints.clippy] ` .
6574
6675### Database Operations
76+
6777- ` just provision-db ` creates the ClickHouse database and tables from ` fixtures/ ` .
6878- ` just reset-db ` drops and recreates tables (destructive operation).
6979- ` just extract-data <FILE> ` exports data to Parquet format.
7080
7181### Justfile Commands
82+
7283Run ` just --list ` to see all available commands. The justfile automates common workflows and should be the preferred method for development tasks.
7384
7485## Coding Style & Naming Conventions
86+
7587- Keep Rust code within 100 columns (enforced by rustfmt).
7688- Use ` rustfmt ` for formatting; it is authoritative and will reorder imports at crate granularity.
7789- Use ` snake_case ` for modules and functions, ` UpperCamelCase ` for types, and reserve ` SCREAMING_SNAKE_CASE ` for constants.
@@ -85,40 +97,49 @@ Run `just --list` to see all available commands. The justfile automates common w
8597## Testing Guidelines
8698
8799### Test Organization
100+
88101- Unit tests live in the same file as the code they test, in a ` #[cfg(test)] ` module.
89102- Integration tests are in the ` tests/ ` directory, organized by feature area.
90103- Shared test utilities and fixtures belong in ` tests/common/ ` .
91104- Async flows rely on ` #[tokio::test] ` , so ensure all async test helpers are properly propagated.
92105
93106### Naming Conventions
107+
94108Name test functions with the behavior under test, following the pattern:
109+
95110- ` <module>_<scenario>_<expected_outcome> `
96111- Examples: ` ingress_rejects_invalid_signature ` , ` forwarder_retries_on_timeout ` , ` entity_scores_spam_bundle_low `
97112
98113### Test Coverage Requirements
114+
99115New behavior must include either:
116+
1001171 . A targeted unit test in the owning module covering the happy path and key edge cases, OR
1011182 . An integration test scenario covering success and error paths
102119
103120### Running Tests
121+
104122- ` just test ` uses nextest for parallel execution (recommended).
105123- ` cargo test ` for standard test runner.
106124- ` cargo test -- --nocapture ` when debugging async failures or inspecting tracing output.
107125- Run ` cargo test --features ... ` if you introduce optional features.
108126
109127### Integration Tests
128+
110129- Integration tests may use ` testcontainers ` to spin up ClickHouse for indexer tests.
111130- Ensure Docker is running before executing integration tests.
112131- Clean up resources in test teardown to avoid port conflicts and leaked containers.
113132
114133### Performance Tests
134+
115135- Benchmark critical paths using Criterion in ` benches/ ` .
116136- Focus on hot paths: validation, signature verification, entity scoring, serialization.
117137- Run ` cargo bench ` to execute all benchmarks and generate performance reports.
118138
119139## Commit & Pull Request Guidelines
120140
121141### Commit Message Style
142+
122143- Follow the short, imperative style seen in history (e.g., ` fix package name ` , ` add builder metrics ` ).
123144- Prefix with scope if it aids triage: ` ingress: ` , ` forwarder: ` , ` entity: ` , ` validation: ` , ` chore: ` , ` fix: ` , ` feat: ` .
124145- Examples:
@@ -127,7 +148,9 @@ New behavior must include either:
127148 - ` chore: bump version to 1.1.3 `
128149
129150### Pull Request Requirements
151+
130152Each PR should include:
153+
1311541 . ** Motivation** : Why is this change needed? What problem does it solve?
1321552 . ** Approach** : High-level overview of the implementation strategy.
1331563 . ** Risky Areas** : Call out potential edge cases, performance impacts, or breaking changes.
@@ -136,46 +159,56 @@ Each PR should include:
1361596 . ** Evidence** : Attach logs, metrics screenshots, or before/after comparisons for user-facing changes.
137160
138161### CI Readiness Checklist
162+
139163Before requesting review, ensure:
164+
140165- [ ] ` cargo build ` succeeds
141166- [ ] ` just fmt ` produces no changes
142167- [ ] ` just clippy ` passes with no warnings
143168- [ ] ` just test ` passes all tests
144169- [ ] Integration tests pass if touching ingress, indexer, or forwarder
145170
146171### Review Process
172+
147173- Address reviewer feedback promptly.
148174- Keep commits focused; avoid mixing refactoring with feature work.
149175- Rebase on ` main ` before merging to maintain a clean history.
150176
151177## Configuration & Runtime Notes
152178
153179### CLI Configuration
180+
154181The proxy is configured through CLI flags defined in ` src/cli.rs ` (` OrderflowIngressArgs ` struct):
182+
155183- ** Required** : ` --user-listen-url ` , ` --system-listen-url ` , ` --builder-name `
156184- ** Optional** : ` --builder-url ` , ` --builder-hub-url ` , ` --orderflow-signer ` , ` --metrics ` , etc.
157185- All flags support environment variable overrides (e.g., ` USER_LISTEN_ADDR ` , ` SYSTEM_LISTEN_ADDR ` ).
158186
159187### Configuration Guidelines
188+
160189When adding new configuration:
190+
1611911 . Document the flag in the struct's ` #[arg(...)] ` annotation with clear help text.
1621922 . Choose safe defaults for local testing (loopback listeners, disabled external services).
1631933 . Update ` --help ` text to reflect behavior changes.
1641944 . Add validation logic in ` src/runner/ ` if the flag affects startup behavior.
1651955 . Update this document's Configuration section if the change is significant.
166196
167197### Runtime Behavior
198+
168199- The proxy uses Tokio's multi-threaded runtime for async operations.
169200- Jemalloc is the default allocator for better memory performance.
170201- Graceful shutdown is coordinated through ` src/tasks/ ` using ` TaskExecutor ` and ` TaskManager ` .
171202- HTTP servers bind to configured addresses and serve JSON-RPC requests via Axum.
172203
173204### Observability
205+
174206- ** Logs** : Structured logging via ` tracing ` (text or JSON format with ` --log.json ` ).
175207- ** Metrics** : Prometheus metrics exposed at ` --metrics ` endpoint (default: disabled).
176208- ** Tracing** : Use ` RUST_LOG ` environment variable for log level control (e.g., ` RUST_LOG=info,flowproxy=debug ` ).
177209
178210### Performance Considerations
211+
179212- Rate limiting is disabled by default; enable with ` --enable-rate-limiting ` .
180213- Gzip compression is disabled by default; enable with ` --http.enable-gzip ` .
181214- Indexing is optional; ClickHouse/Parquet indexers only run if configured.
@@ -185,6 +218,7 @@ When adding new configuration:
185218## Architecture & Design Patterns
186219
187220### Data Flow Overview
221+
1882221 . ** Ingress** receives bundles/transactions via JSON-RPC over HTTP
1892232 . ** Validation** checks transaction intrinsics, signatures, and bundle structure
1902243 . ** Entity Scoring** computes priority based on sender reputation and bundle characteristics
@@ -195,24 +229,28 @@ When adding new configuration:
195229### Common Patterns
196230
197231#### Error Handling
232+
198233- Use ` eyre::Result ` for most fallible operations.
199234- Use ` thiserror ` for domain-specific error types with context.
200235- Log errors at appropriate levels: ` error! ` for unexpected failures, ` warn! ` for recoverable issues.
201236- Return structured errors from public APIs; log internal errors with context.
202237
203238#### Async Patterns
239+
204240- Spawn long-running tasks using ` TaskExecutor ` and ` TaskManager ` for graceful shutdown.
205241- Use ` tokio::select! ` for concurrent operations with cancellation support.
206242- Prefer bounded channels (` tokio::sync::mpsc ` ) over unbounded to prevent memory growth.
207243- Use ` Arc<RwLock> ` or ` Arc<Mutex> ` for shared mutable state; prefer immutable sharing when possible.
208244
209245#### Observability Patterns
246+
210247- Instrument public functions with ` #[tracing::instrument] ` for automatic span creation.
211248- Use structured fields in log messages: ` tracing::info!(entity = %addr, "processing bundle") ` .
212249- Emit metrics for critical operations: request counts, latencies, queue depths, error rates.
213250- Add custom metrics in ` src/metrics.rs ` using the ` metrics ` crate.
214251
215252#### Testing Patterns
253+
216254- Mock external dependencies using trait abstractions (see ` PeerStore ` trait in ` builderhub.rs ` ).
217255- Use builder patterns for complex test fixtures.
218256- Leverage ` proptest ` for property-based testing of validation logic.
@@ -229,6 +267,7 @@ When adding new configuration:
229267### Dependencies & Ecosystem
230268
231269Key dependencies and their roles:
270+
232271- ** ` alloy ` ** : Ethereum primitives (transactions, signatures, addresses)
233272- ** ` rbuilder-primitives ` ** : BuilderNet-specific bundle types
234273- ** ` axum ` ** : HTTP framework for JSON-RPC APIs
@@ -241,14 +280,17 @@ Key dependencies and their roles:
241280- ** ` criterion ` ** : Performance benchmarking
242281
243282### Performance Hotspots
283+
244284Monitor and optimize these areas:
285+
2452861 . ** Signature Verification** : Uses ` alloy ` for ECDSA recovery; consider batching.
2462872 . ** Entity Scoring** : Computed per bundle; cache aggressively.
2472883 . ** Validation** : Runs on every transaction; keep logic fast and allocate minimally.
2482894 . ** Serialization** : JSON-RPC parsing and encoding; consider message size limits.
2492905 . ** Queue Operations** : High contention on shared queues; use per-level locks.
250291
251292### Security Considerations
293+
252294- Validate all user inputs before processing (see ` validation.rs ` ).
253295- Rate limit by entity to prevent spam and DoS attacks.
254296- Reject bundles from entities with low scores (spam detection).
0 commit comments