> For the complete documentation index, see [llms.txt](https://hertzflow.gitbook.io/hertzflow-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hertzflow.gitbook.io/hertzflow-docs/tech-docs/smart-contract.md).

# Smart Contract

## Overview

### Architecture

#### Design Principles

1. **Modularity**: Contracts are separated by function for upgradeability
2. **Data Separation**: State is stored in dedicated DataStore
3. **Event-Driven**: All actions emit events through EventEmitter
4. **Two-Step Execution**: Actions require request creation then keeper execution

#### Contract Categories

**Bank Contracts**

Hold funds for the protocol:

* `DepositVault` - Holds deposit collateral
* `WithdrawalVault` - Holds withdrawal tokens
* `OrderVault` - Holds order collateral
* `GlvVault` - Holds HLV vault tokens
* `ShiftVault` - Holds shift operation tokens

**Data Storage**

* `DataStore` - Primary key-value data storage
* `RoleStore` - Access control management
* `OracleStore` - Oracle signer management

**Exchange Contracts**

User-facing interaction points:

* `ExchangeRouter` - Create deposits, withdrawals, orders
* `Router` - Token approval management
* `GlvRouter` - HLV-specific operations

**Handler Contracts**

Execute user requests:

* `DepositHandler` - Execute deposits
* `WithdrawalHandler` - Execute withdrawals
* `OrderHandler` - Execute orders
* `LiquidationHandler` - Execute liquidations
* `AdlHandler` - Auto-deleverage positions
* `GlvDepositHandler` - Execute HLV deposits
* `GlvWithdrawalHandler` - Execute HLV withdrawals

**Reader Contracts**

Query protocol state:

* `Reader` - Market and position data
* `GlvReader` - HLV vault data

**Factory Contracts**

Create new protocol entities:

* `MarketFactory` - Create new markets
* `GlvFactory` - Create new HLV vaults

**Oracle Contracts**

Price feed management:

* `Oracle` - Price validation and caching
* `ChainlinkPriceFeedProvider` - Chainlink integration

### Price Oracle Architecture

Accurate and tamper-resistant price discovery is a cornerstone of the Hertzflow protocol. Our oracle design balances **decentralization, reliability, and latency requirements** to serve both trading and risk management functions.

The Hertzflow oracle design ensures:

* **Primary reliance** on decentralized, manipulation-resistant feeds (Pyth).
* **Automatic degradation** to high-quality CEX index prices when needed.
* **Liquidity-aware weighting** for fallback aggregation.
* **Multi-layer resiliency** with redundancy at both the runtime and infrastructure levels.

#### Aggregator Strategy

* **Primary Source – Pyth Network**\
  Hertzflow prioritizes high-frequency decentralized price streams from **Pyth Network**. Pyth aggregates prices and confidence intervals from multiple independent publishers, applying a PoS-weighted mechanism to produce manipulation-resistant reference prices.
* **Fallback Source – CEX Index Prices**\
  If Pyth data is unavailable or stale beyond **3 seconds**, the system degrades gracefully to an **index price feed** aggregated from leading centralized exchanges (Binance, OKX, Bybit).

#### Update Frequency

* **Latency Guarantees**\
  **p99 latency**: ≤ 1–2 seconds, ensuring keepers' liquidation and settlement logic remains real-time.\
  **p999 latency**: bounded by a stricter upper limit (configurable) to guarantee global stability under stress conditions.

#### Oracle Node Selection

* **Decentralized Path (Preferred)**: Pyth Network for resilient, publisher-aggregated price feeds. To eliminate reliance on third-party APIs and avoid rate limits, we self-host Pyth's core infrastructure components including `pythnet-rpc`, `wormhole-spy`, and `hermes`.
* **Centralized Path (Fallback)**: CEX feeds selected strictly from venues with top-tier depth and reputation (Binance, OKX, Bybit). Feeds are consumed via WebSocket subscriptions to minimize latency. Redundancy across exchanges ensures continuity even if individual feeds degrade.

#### Slippage Protection Mechanism

When fallback aggregation relies on CEX data, Hertzflow enforces a **liquidity-weighted scoring system** to prioritize healthier order books:

* **Depth Score (a):** Sum of bid/ask liquidity within ±1% of current price.
* **Support Ratio (b):** Ratio of near-book (top 3 levels) to mid-book liquidity, measuring order book resilience.
* **Balance Score (c):** Relative balance of total bids vs. asks, reflecting buy/sell symmetry.

The composite score is calculated as:

$$
Score\_{exchange} = w\_1 × a + w\_2 × b + w\_3 × c
$$

Scores are used as weights in the final aggregated index, ensuring **high-liquidity venues contribute more heavily** to the effective oracle price.

#### Exception Handling & Failover

To maintain uninterrupted pricing, the system implements **multi-layered resiliency mechanisms**:

* **Real-Time Failover**: Wait up to **3s** for Pyth updates. If data remains stale, immediately switch to the fallback CEX index.
* **Continuity Assurance**:
  * **Quick Fixer**: Patches short-term gaps detected at runtime.
  * **Gap Fixer**: Scheduled process validating DB continuity and repairing missed intervals.
  * **Lazy Filler**: On-demand backfill during query time for external consumers.
* **Architecture-Level Redundancy**: Fetcher and Aggregator services run in **active-active multi-instance mode**, eliminating single points of failure.

## Key Flows

#### Deposit Flow

```
User → ExchangeRouter.createDeposit → DepositVault
Keeper → DepositHandler.executeDeposit → MarketToken minted
```

#### Order Flow

```
User → ExchangeRouter.createOrder → OrderVault
Keeper → OrderHandler.executeOrder → Position updated
```

#### Withdrawal Flow

```
User → ExchangeRouter.createWithdrawal → WithdrawalVault
Keeper → WithdrawalHandler.executeWithdrawal → Tokens returned
```

### Security Model

#### Roles

| Role           | Permissions              |
| -------------- | ------------------------ |
| ROLE\_ADMIN    | Grant/revoke roles       |
| CONTROLLER     | Execute protocol actions |
| ORDER\_KEEPER  | Execute orders           |
| CONFIG\_KEEPER | Update configuration     |

#### Access Control

* All state-changing functions require appropriate roles
* Timelock for sensitive configuration changes
* Multi-sig for critical operations


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hertzflow.gitbook.io/hertzflow-docs/tech-docs/smart-contract.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
