# Architecture

This page explains how the Tycho Market Maker is structured and how its components work together.

### System Overview

The market maker is built as a Rust library with two binary applications.

* maker - The core trading engine that monitors pools and executes trades
* monitor - An optional service that subscribes to Redis events and persists them to PostgreSQL

Both binaries share the same core library and communicate via Redis pub/sub for real-time event streaming.

### High-Level Flow

1. Load configuration (TOML + ENV)
2. Initialise blockchain provider and wallet
3. Start price feed monitoring (Binance or Chainlink implemented)
4. Poll Tycho API for pool states
5. Compare reference price vs. pool price
6. If profitable → build transaction → submit to chain
7. Publish trade event to Redis
8. Monitor service saves event to PostgreSQL
9. Repeat from step 4

### Core Components

Market Maker Engine is the main orchestrator that:

* Fetches current prices from the configured feed
* Queries Tycho for pool states and swap simulations
* Calculates profitability (spread - gas - slippage)
* Decides when to execute trades
* Publishes events to Redis

Runs in a loop with configurable polling intervals.

**Price Feed System** (reference) is a factory pattern that creates the appropriate price feed based on configuration, for now

`pub enum PriceFeed { Binance(BinanceFeed), Chainlink(ChainlinkFeed) }`

* Binance Feed - WebSocket connection for real-time CEX prices
* Chainlink Feed - On-chain oracle queries for decentralised pricing

The factory allows easy switching between feeds without changing the core logic.

### Tycho Integration

Handles all interactions with the Tycho Protocol:

* Fetching pool states via HTTP API
* Running swap simulations to get expected output amounts
* Building swap calldata for transactions

Uses the tycho-client and tycho-simulation crates.

### Execution Strategies

Chain-specific transaction building and submission:

* mainnet.rs - Ethereum with Flashbots support for MEV protection
* base.rs - Base L2 with optimised gas handling
* unichain.rs - Unichain-specific configurations

Each strategy implements transaction building, gas estimation, and submission logic tailored to its network.

### Key Design Patterns

* Factory Pattern: price feeds and execution strategies are instantiated dynamically based on configuration:
* Builder Pattern: MarketMakerBuilder assembles components with validation:

Components communicate via Redis pub/sub instead of direct coupling. The maker doesn't know about the database, it just publishes events.

Automatic Recovery : the maker binary wraps the main loop in a panic handler that restarts on failure with exponential backoff.

### Trade Execution Flow

1. Price DiscoveryFetch current price from CEX feed (e.g., ETH/USDC from Binance)
2. Pool QueryRequest available pools from Tycho API for the token pair
3. SimulationFor each pool, simulate a swap to get expected output and gas cost
4. Profitability Check
5. Transaction Building: chain executor builds transaction with appropriate gas/bundle settings
6. Submission: Submit via standard RPC or Flashbots / Flashblocks
7. Event PublishingPublish result to Redis for monitoring
8. PersistenceMonitor service writes to PostgreSQL

### RPC Usage

This market maker is RPC intensive due to continuous polling. Each cycle queries token balances, gas prices, and block numbers.

Estimated RPC usage with default config:

* \~5-10 RPC calls per cycle
* Mainnet
  * Poll interval: 6000ms
  * Mainnet (6s): \~1 request/second = 70k-140k requests/day
* Unichain or other L2
  * Poll interval: 500ms, mostly depends on block time
  * \~10-20 requests/second = 850k-1.7M requests/day (can be drastically reduced)

Recommendations

* Use dedicated node or RPC providers with high rate limits (Alchemy, QuickNode)
* Avoid free tier public RPCs or use local proxies forward to multiple RPCs
* Adjust poll\_interval\_ms based on your RPC plan limits

For production, budget for at least 100k-500k daily RPC requests per maker instance.

### Monitoring Service

A standalone binary that handles event/trade persistence.

The monitor program subscribes to Redis pub/sub channels and persists all market maker events to PostgreSQL. It runs independently from the maker binary and doesn't require blockchain access.

The monitor service handles all database writes, keeping the maker lightweight.

**What it does:**

* Listens to Redis events published by maker instances
* Stores trade history in PostgreSQL via SeaORM
* Tracks configuration changes and system metrics
* Provides queryable historical data for analysis

Multiple maker instances can publish to the same Redis channel, and a single monitor service handles persistence for all of them.

Data Persistence is done via PostgreSQL + SeaORM for:

* Trade history
* Profit/loss tracking
* Error logs
* Performance analytics

**Environment Configuration:**

* `DATABASE_URL` - PostgreSQL connection string
* `DATABASE_NAME` - Target database
* `TESTING` - Testing mode flag
* `HEARTBEAT` - Optional uptime monitoring URL
