Hydra AMM
Universal AMM engine: build, configure, and operate any Automated Market Maker through a unified interface.
Hydra AMM is a Rust library that provides a common set of traits, domain types, and feature-gated pool implementations covering the six major AMM families found across DeFi. Use it as a foundation to build your own AMM, simulate swap scenarios, or integrate multiple pool types into a single system.
Supported AMM Families
| Family | Invariant / Model | Real-World Examples | Feature Flag |
|---|---|---|---|
| Constant Product | x · y = k | Uniswap v2, SushiSwap, Raydium CPMM, PancakeSwap | constant-product |
| Concentrated Liquidity (CLMM) | Tick-based ranges | Uniswap v3/v4, Orca Whirlpools, Raydium CLMM, Trader Joe LB | clmm |
| Hybrid / StableSwap | Curve amplified invariant | Curve Finance, Aerodrome/Velodrome, Thorchain | hybrid |
| Weighted Pools | ∏(Bᵢ^Wᵢ) = k | Balancer 80/20, multi-token pools | weighted |
| Dynamic / Proactive MM | Oracle-driven pricing | DODO PMM, Meteora DLMM, Lifinity, KyberSwap DMM | dynamic |
| Order Book Hybrid | CLOB + AMM fallback | Phoenix | order-book |
Architecture
The crate is organized into six layers, each building on the previous:
┌─────────────────────────────────────────────────┐
│ Layer 5: Factory & Dispatch │
│ DefaultPoolFactory · PoolBox enum dispatch │
├─────────────────────────────────────────────────┤
│ Layer 4: Pool Implementations (feature-gated) │
│ ConstantProduct · CLMM · Hybrid · Weighted │
│ Dynamic · OrderBook │
├─────────────────────────────────────────────────┤
│ Layer 3: Configuration │
│ AmmConfig enum · 6 config structs │
├─────────────────────────────────────────────────┤
│ Layer 2: Core Traits │
│ SwapPool · LiquidityPool · FromConfig │
├─────────────────────────────────────────────────┤
│ Layer 1: Domain Types │
│ Token · Amount · Price · Tick · Position │
├─────────────────────────────────────────────────┤
│ Layer 0: Math & Precision │
│ Precision trait · CheckedArithmetic · Rounding │
└─────────────────────────────────────────────────┘
Key design principles:
- Configuration-driven: Pools are created from declarative
AmmConfigstructs via a factory. - Zero-cost abstractions: Enum dispatch (
PoolBox) instead ofdyntrait objects — no vtable overhead. - Checked arithmetic: All operations are explicitly checked for overflow/underflow. No panics in library code.
- Newtypes everywhere:
Amount,Price,Tick,FeeTier, etc. — no raw primitives in public API. - Feature-gated: Each pool type is behind its own Cargo feature. Compile only what you need.
Installation
Add hydra-amm to your project:
Or add it manually to your Cargo.toml:
[]
= "0.1"
This enables all pool types by default. To select only the pool types you need:
[]
= { = "0.1", = false, = ["std", "constant-product", "clmm"] }
Feature Flags
| Feature | Default | Description |
|---|---|---|
std |
✅ | Standard library support (BTreeMap storage, Display impls) |
fixed-point |
❌ | I80F48 fixed-point arithmetic via the fixed crate |
float |
❌ | f64 floating-point arithmetic (implies std) |
constant-product |
✅ | Constant product (x·y=k) pool |
clmm |
✅ | Concentrated Liquidity Market Maker pool |
hybrid |
✅ | Hybrid / StableSwap pool (Curve-style) |
weighted |
✅ | Weighted pool (Balancer-style) |
dynamic |
✅ | Dynamic / Proactive Market Maker pool (DODO-style) |
order-book |
✅ | Order Book Hybrid pool (uses orderbook-rs) |
all-pools |
✅ | Convenience: enables all six pool types |
Minimal Dependency Example
For an on-chain environment that only needs constant-product swaps with fixed-point math:
[]
= { = "0.1", = false, = ["fixed-point", "constant-product"] }
Quick Start
Creating a Constant Product Pool and Executing a Swap
use ;
use ;
use DefaultPoolFactory;
use SwapPool;
// 1. Define two tokens (32-byte addresses + decimal precision)
let usdc = new;
let weth = new;
// 2. Build a Constant Product pool configuration
let pair = new.expect;
let fee = new; // 0.30% fee
let config = ConstantProduct;
// 3. Create the pool via the factory
let mut pool = create.expect;
// 4. Execute a swap (sell 10 000 units of token A for token B)
let spec = exact_in.expect;
let result = pool.swap.expect;
assert!;
assert!;
Advanced: CLMM Pool with Concentrated Liquidity Positions
use ;
use ;
use DefaultPoolFactory;
use ;
// 1. Define tokens
let tok_a = new;
let tok_b = new;
let pair = new.expect;
// 2. Configure a CLMM pool at tick 0, tick spacing 10
let fee = new;
let initial_position = new.expect;
let config = Clmm;
// 3. Create pool and add more liquidity
let mut pool = create.expect;
let add = add
.expect;
let _ = pool.add_liquidity;
// 4. Execute a swap
let spec = exact_in.expect;
let result = pool.swap.expect;
assert!;
Implementing a Custom Pool
Implement the SwapPool trait for your own AMM type:
use SwapPool;
use ;
use AmmError;
Module Structure
hydra_amm/
├── error — AmmError enum (code ranges 1000-4999)
├── domain — Token, Amount, Price, Tick, Position, SwapSpec, SwapResult, ...
├── math — Precision trait, CheckedArithmetic, Rounding, tick math
├── traits — SwapPool, LiquidityPool, FromConfig
├── config — AmmConfig enum + per-pool config structs
├── pools — Feature-gated pool implementations + PoolBox dispatch enum
├── factory — DefaultPoolFactory::create()
└── prelude — Convenience re-exports for common types and traits
Safety and Correctness
This crate prioritizes correctness above all:
unsafecode is denied — enforced at the compiler level- No
.unwrap()/.expect()/panic!— denied via Clippy lints in library code - Checked arithmetic — all operations return
OptionorResult - Explicit rounding — all divisions specify rounding direction (up or down, always against the user)
- Overflow checks enabled in both debug and release profiles
- Property-based testing with
proptestfor invariant validation - 30 doc-tests — all code examples in documentation are compiled and executed
API Reference
Full API documentation is available on docs.rs/hydra-amm.
Development
Prerequisites
- Rust (edition 2024, see
rust-toolchain.toml) - Make
Common Commands
# Build
# Test
# Quality
# Documentation
# Coverage
# Benchmarks
Pre-Push Checklist
Always run before pushing:
This executes: cargo fix → cargo fmt → cargo clippy → cargo test → cargo doc
AMM Classification
The following diagram shows the AMM landscape covered by this crate:
Automated Market Makers
├── Constant Product (x·y=k)
│ ├── Uniswap v2
│ ├── SushiSwap
│ ├── QuickSwap
│ ├── Raydium (CPMM)
│ └── PancakeSwap
├── Concentrated Liquidity (CLMM)
│ ├── Uniswap v3 / v4
│ ├── Orca (Whirlpools)
│ ├── Raydium (CLMM)
│ ├── Trader Joe (Liquidity Book)
│ ├── Maverick
│ ├── Ambient Finance
│ ├── Cetus Protocol
│ ├── Camelot
│ └── iZUMi (DL-AMM)
├── Hybrid / StableSwap
│ ├── Curve Finance
│ ├── Aerodrome / Velodrome
│ └── Thorchain (Orbital Pools)
├── Weighted Pools
│ └── Balancer (80/20, multi-token)
├── Dynamic / Proactive MM
│ ├── DODO (PMM)
│ ├── Meteora (DLMM)
│ ├── Lifinity
│ └── KyberSwap (DMM)
└── Order Book Hybrid
└── Phoenix (CLOB on Solana)
Contributing
Contributions are welcome! Please follow these guidelines:
- Fork the repository and create a feature branch
- Read the documentation in
.internalDoc/(especially09-RUST-GUIDELINES.md) - Write tests for all new public functions
- Run
make pre-pushbefore submitting - Create a PR with a clear description
Code Standards
- All comments and documentation in English
///doc comments on every public item#[must_use]on all pure functions- Checked arithmetic only — no panics in library code
- Newtypes for all domain concepts
License
This project is licensed under the MIT License — see the LICENSE file for details.
Contact
- Author: Joaquín Béjar García
- Email: jb@taunais.com
- Telegram: @joaquin_bejar
- Repository: github.com/joaquinbejar/hydra-amm
- Crates.io: crates.io/crates/hydra-amm
- Documentation: docs.rs/hydra-amm