diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..cede0c5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: CI + +on: + push: + branches: [master, main, fix/**, feature/**] + pull_request: + branches: [master] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-rust@v1 + with: + rust-version: stable + - name: Install toolchain components + run: rustup component add clippy rustfmt + - name: Check formatting + run: cargo fmt --all -- --check + - name: Run clippy + run: cargo clippy --all-targets --all-features -- -D warnings + - name: Build + run: cargo build --all-targets --verbose + - name: Test + run: cargo test --all-features --verbose diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..94988ce --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,35 @@ +# Contributing to cowSolver + +Thank you for your interest in improving **cowSolver**! Contributions are welcome and appreciated. These guidelines help maintain a high-quality and well-organized codebase. + +## Reporting Issues + +- Use GitHub issues to report bugs, suggest enhancements or request new features. +- Include as much detail as possible (steps to reproduce, expected vs. actual behaviour, environment info). +- Search existing issues before opening a new one to avoid duplicates. + +## Pull Requests + +- Fork this repository and create a feature branch (e.g., `feature/your-feature-name`). +- Write clear, descriptive commit messages and reference relevant issues using keywords like `Closes #`. +- Follow the existing code style and run `cargo fmt` before committing to ensure consistent formatting. +- Ensure the project builds and all tests pass (`cargo test`). Add new tests to cover your changes. +- Update documentation and README files when adding new modules or altering existing behaviour. +- Submit your pull request against the `master` branch with a detailed description of your changes and any additional context. + +## Coding Standards + +- The project uses **Rust 2021** and adheres to idiomatic Rust practices. +- Use explicit error types with `Result` for error handling. Avoid using `unwrap()` or panics in library code. +- Keep functions small and focused; break complex logic into smaller units when possible. +- Run `clippy` to catch potential issues and follow its suggestions where appropriate. + +## Communication & Conduct + +- Be respectful and constructive in discussions. We strive to maintain an inclusive and collaborative community. +- Participate in code reviews by providing thoughtful feedback and suggestions for improvement. +- If you have questions about the code or architecture, feel free to open a discussion or reach out via issues. + +## License + +By contributing to this project, you agree that your contributions will be licensed under the [MIT License](LICENSE). diff --git a/README.md b/README.md index 645841e..a6d762d 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,81 @@ # cowSolver -**High-performance cross-chain solver implementation for the CoW Protocol** +[![CI](https://github.com/0xDevNinja/cowSolver/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/0xDevNinja/cowSolver/actions/workflows/ci.yml) -cowSolver is a Rust-based solver engine designed to enable seamless token swaps across multiple blockchain networks with optimal routing and settlement. Its modular architecture covers batch auction processing, order matching, AMM routing, pricing engine, domain models, math utilities, adapters for chain RPC and DEX integrations, bridge integration, and advanced solving strategies. +## Overview -## Components +cowSolver is a high-performance cross-chain solver implementation for the CoW Protocol. It enables seamless token swaps across multiple blockchain networks with optimal routing and settlement. The project is written in Rust and is composed of modular components that can be independently extended and tested. + +## Architecture + +The solver consists of several layers: - **Solver Engine** – Handles batch auction processing and orchestration. -- **Order Matching** – Supports CoW discovery with direct pair and ring matching. -- **AMM Routing** – Provides multi-hop routing through Uniswap, Balancer, Curve, and other decentralized exchanges. -- **Pricing Engine** – Calculates uniform clearing prices using multiple strategies. -- **Domain Models** – Defines orders, tokens, chains, and settlement structures. -- **Math Utilities** – Includes pricing calculations and decimal handling. -- **Adapters Layer** – Integrates with chain RPC clients and various DEX protocols. -- **Bridge Integration** – Manages cross-chain settlement execution. -- **Strategy Layer** – Implements advanced solving strategies such as ring trades and multi-venue optimization. -- **CLI Binary** – Offers a command-line interface for solver operations. -- **Daemon Service** – Provides a long-running solver service with API endpoints. -- **Integration Tests** – Ensures correctness through end-to-end tests. -- **Performance Optimization** – Focuses on gas optimization and parallel processing. +- **Order Matching** – Performs CoW discovery and matches orders via direct pairs and rings. +- **AMM Routing** – Computes optimal multi-hop routing through AMMs like Uniswap, Balancer and Curve. +- **Pricing Engine** – Calculates clearing prices using uniform or volume-weighted strategies. +- **Domain Models** – Defines structs for orders, tokens, chains and settlements. +- **Math Utilities** – Provides precise decimal arithmetic and slippage calculations. +- **Adapters Layer** – Implements chain RPC clients and DEX integrations for on-chain interactions. +- **Bridge Integration** – Executes cross-chain settlements using bridges. +- **Strategy Layer** – Houses solving strategies with pluggable heuristics. +- **CLI Binary** – Offers command-line interface for interacting with the solver. +- **Daemon Service** – Provides a long-running service with HTTP/gRPC APIs. +- **Integration Tests** – Validates end-to-end flows across modules. +- **Performance Optimizations** – Contains utilities for improving throughput and reducing gas. + +See the [docs/architecture.md](docs/architecture.md) guide for a detailed diagram and explanation of how these components interact. ## Getting Started -This repository currently contains the initial skeleton of the project. To build and run the project: +### Prerequisites + +- Rust 1.75 or later installed (`rustup toolchain install stable`) +- Cargo for building and testing +- (Optional) Docker for running local testnets + +### Building and Running + +Clone the repository and run: + +```bash +git clone https://github.com/0xDevNinja/cowSolver.git +cd cowSolver +cargo build --release +cargo test +``` + +To start the daemon service: + +```bash +cargo run --bin daemon -- --help +``` + +### CLI Usage + +The CLI binary is located in `src/bin/cli.rs`. Build and run it: ```bash -# Ensure Rust and Cargo are installed -rustc --version -cargo --version +cargo run --bin cli -- run +cargo run --bin cli -- submit --order-file examples/order.json +``` + +Use `--help` with any subcommand to see available options. + +### Enabling Chainstore Fallback -# Build the crate -cargo build +Some features such as cross-chain settlement rely on external services. To enable the optional chainstore fallback for fetching missing blocks via Bitswap, set the following environment variable: + +```bash +export FOREST_ENABLE_CHAINSTORE_FALLBACK=1 ``` -Further modules and implementations will be added incrementally through issues and pull requests. +See the [Chainstore Fallback guide](docs/chainstore_fallback.md) for more details. + +## Contributing + +We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, coding guidelines, and instructions for submitting issues and pull requests. + +## License + +This project is licensed under the MIT License. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..8ee75bb --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,38 @@ +# Architecture + +The **cowSolver** project is structured as a modular Rust crate with clear separation of concerns. The high-level components include: + +- **Domain models** (`models`): Defines fundamental data structures like `Order`, `Token`, `ChainId`, and `Settlement`. These types model orders, tokens, blockchain identifiers, and settlement receipts. +- **Solver engine** (`solver`): Orchestrates batch auctions. It collects orders, groups them into auctions, and delegates matching, routing and pricing to other modules. The engine exposes traits (`BatchAuction`, `Solver`) to allow custom implementations. +- **Order matching** (`matching`): Implements algorithms to find complementary orders. Current implementations include `PairMatcher` and `RingMatcher`, which discover direct and cyclic match opportunities. +- **AMM routing** (`routing`): Computes optimal multi-hop routes across automated market makers such as Uniswap, Balancer and Curve. Each protocol has its own router that implements a common `AmmRouter` trait. +- **Pricing engine** (`pricing`): Calculates clearing prices for auctions. Strategies like uniform pricing and volume-weighted pricing can be added by implementing the `PricingEngine` trait. +- **Math utilities and performance** (`utils`, `performance`): Provide decimal arithmetic helpers, slippage calculations, normalization functions and sorting/optimization utilities. +- **Adapters** (`adapters`): Abstract RPC clients and decentralized exchange integrations. Traits like `ChainRpcClient` and `DexAdapter` allow plugging in real node clients and DEX interfaces. +- **Bridge integration** (`bridge`): Provides a `BridgeAdapter` trait for executing settlements across chains. A dummy adapter is included; real implementations can connect to protocols such as Hop or Connext. +- **Strategy layer** (`strategy`): Defines pluggable solver strategies (e.g., baseline, advanced). Each strategy implements the `Strategy` trait and dictates how orders are grouped and priced. +- **Daemon service** (`daemon`): A long-running service built with Tokio that periodically runs the solver and exposes an HTTP or gRPC API for managing orders and retrieving settlements. +- **Command-line interface** (`src/bin/cli.rs`): Offers a user-friendly CLI built with Clap to run the solver, submit orders, or execute integration tests. + +## Data Flow + +1. **Order ingestion:** Orders are created and validated using the `models` module and stored in an in-memory or persistent store. +2. **Batch formation:** The solver engine groups orders into batch auctions based on timing or external triggers. +3. **Matching:** For each auction, the `matching` module discovers matching sets of orders using pair and ring matching strategies. +4. **Routing:** The routing layer computes optimal swap paths across supported AMMs for each potential match. +5. **Pricing:** The pricing engine calculates a uniform clearing price (or other strategies) that satisfies all matches. +6. **Settlement:** The result is packaged into a `Settlement` structure and executed on chain. If the target chain differs from the order chain, the bridge adapter handles cross-chain execution. +7. **Performance & Metrics:** Utilities and performance modules collect metrics, optimize gas usage, and ensure the solver scales efficiently. + +## Extensibility + +The architecture is intentionally modular. To add new functionality: + +- Implement additional `Matcher` strategies in `matching` for novel order matching patterns. +- Add new routers in `routing` to support other AMMs or DEX aggregators. +- Provide alternative pricing strategies by implementing `PricingEngine`. +- Integrate real blockchain nodes and DEXs by implementing `ChainRpcClient` and `DexAdapter`. +- Introduce real bridge protocols by implementing `BridgeAdapter`. +- Build more sophisticated solver strategies in the `strategy` layer. + +This modular design facilitates industry-level adoption, allowing the solver to evolve alongside the rapidly changing decentralized finance landscape. diff --git a/docs/chainstore_fallback.md b/docs/chainstore_fallback.md new file mode 100644 index 0000000..22f7019 --- /dev/null +++ b/docs/chainstore_fallback.md @@ -0,0 +1,23 @@ +# Chainstore Fallback + +Forest includes an **optional chainstore fallback** mechanism that allows the node to fetch missing blocks from the network when they are absent from the local database. This behaviour mirrors the Lotus node's `LOTUS_ENABLE_CHAINSTORE_FALLBACK` feature and can help keep the chainstore in sync when running on archival or non-validating nodes. + +## Enabling Fallback + +To activate the fallback mechanism, set the environment variable `FOREST_ENABLE_CHAINSTORE_FALLBACK` to `true` when starting the node. For example: + +``` +FOREST_ENABLE_CHAINSTORE_FALLBACK=true forest +``` + +When fallback is enabled, the chainstore attempts to read blocks from the local store. If a block is not found, the fallback implementation invokes Bitswap via the `BitswapRequestManager` to fetch the missing block from peers. Once retrieved, the block is cached in the local store and returned to the caller. If the environment variable is unset or set to any other value, the chainstore operates in strict mode and returns an error when data is missing. + +## Considerations + +- **Network traffic:** Fetching data from peers incurs additional network traffic and latency. Enable fallback primarily for archival or non-validating nodes where occasional missing data is acceptable. +- **Performance:** Fallback may slow down block validation since the node must wait for network retrieval. Ensure your node monitors logs and performance metrics when using this feature. +- **Experimental status:** This feature is experimental and may evolve. Review updates to ensure compatibility with future protocol or network changes. + +## Implementation Details + +The fallback logic is implemented in the file `src/chain/store/blockstore_fallback.rs`. It provides a `FallbackBlockstore` wrapper that checks the `FOREST_ENABLE_CHAINSTORE_FALLBACK` environment variable and invokes Bitswap if necessary. See the source for more details on error handling and integration with the existing `ChainStore`.