Site icon Chainstack

Hyperliquid architecture: Clearinghouse and Agent Keys

Chainstack banner: Hyperliquid Architecture — Clearinghouse, Agent Keys, Cross-Margin

If you’ve been following my recent series on EVM storage slots and the granular mechanics of Solana’s Token-2022 extensions, you know that optimizing smart contract architecture is ultimately an endless battle against the underlying execution environment. Whether we are writing Solidity, Vyper, or Rust, we spend our careers trying to squeeze maximum performance out of systems designed to do a million different things.

But what if you didn’t have to compromise? What if, instead of fighting the virtual machine, you built a Layer 1 blockchain from the ground up to do exactly one thing perfectly?

This is the premise of Hyperliquid.

In Part 1 of this new series, we are going to step away from generic execution environments and zoom out to look at the macro-architecture of an App-Chain. Specifically: the Clearinghouse as a unified state tree, Hyperliquid Agent Keys and how they enable bot trading without MetaMask, and native cross-margin across spot and perpetual positions.

The L1 dilemma: why build a sovereign chain?

To understand what Hyperliquid is, we have to look at the specific engineering problem it was built to solve: creating a fully on-chain Central Limit Order Book (CLOB) that can mathematically rival the latency of centralized exchanges.

When protocol engineers attempt to build high-frequency trading engines on existing blockchains, they inevitably hit a wall at the state-transition layer.

The Ethereum & Rollup Bottleneck The EVM is a global, sequential state machine. Every transaction must be processed one after the other. More importantly, general-purpose VMs carry a massive “latency tax” because they must dynamically meter gas for every computation.

When a user places an order on a generic rollup, the VM must load the contract, parse the calldata, execute generic opcodes, and write to the state trie. For a market maker trying to update their quotes 1,000 times a second to avoid arbitrage, dynamically metering generic bytecode is incredibly inefficient.

The Solana Bottleneck Solana seemingly solves the sequential problem via the Sealevel parallel runtime. By requiring transactions to declare their read/write accounts upfront, the SVM can process non-overlapping transactions simultaneously.

However, an order book inherently requires shared state. If a thousand users are trading the SOL/USDC pair, they must all mutate the exact same market account (the PDA). Because they are fighting over the same data structure in memory, this creates state contention. The parallelization engine degrades into a single-lane highway, hard-capping the maximum theoretical throughput for that specific market and forcing sequential execution anyway.

The App-Chain Solution Hyperliquid was invented because the founders realized a fundamental architectural truth: To achieve sub-millisecond finality and handle 100,000+ orders per second, the order book cannot live inside a smart contract. The order book must BE the blockchain.

The dual-engine architecture: HyperCore & HyperEVM

Hyperliquid solves the app-chain composability problem with a dual-engine architecture: HyperCore, a closed state machine handling all order book operations natively in memory, and HyperEVM, a full EVM environment where Solidity contracts can read HyperCore state in real time via precompiles — no bridge, no oracle lag. Both engines share the same block space and consensus layer, HyperBFT. For a full breakdown of this architecture, see What is Hyperliquid? — this article picks up from there.

The Сlearinghouse: unified state & native cross-margin

If HyperCore is the engine, the Clearinghouse is the database.

In traditional finance, a clearinghouse is a centralized entity that sits between buyers and sellers to guarantee trades, manage margin requirements, and execute liquidations. In traditional DeFi, this role is awkwardly duct-taped together using fragmented smart contracts.

Let’s look at the generic VM approach to margin: If you want to trade Spot and Perps on an Ethereum rollup, you are dealing with entirely separate state islands. Your Spot assets sit in a Uniswap liquidity pool or your wallet. Your Perp margin sits inside a specific vault contract. If you own 1 Spot BTC and want to use it as collateral to short ETH, you have to execute multiple transactions: borrow USDC against your BTC on some platform, bridge it to a perp DEX, and deposit it into their margin contract.

This state fragmentation leads to massive capital inefficiency and smart contract risk.

The Hyperliquid solution: The L1 as the Clearinghouse

In Hyperliquid, the Clearinghouse isn’t a smart contract, it is the fundamental state tree of the HyperCore L1. Because the developers control the actual execution client, they built a unified data structure that natively understands a user’s portfolio as a single, global entity. To see exactly how this unified state is managed, we can look at the data structures required to deserialize the L1’s clearinghouseState via the API.

Here is the actual Rust representation of a user’s Clearinghouse state, as seen in standard Hyperliquid SDKs:

use serde::{Deserialize, Serialize};

// The root state object returned by the L1 Clearinghouse
#[derive(Serialize, Deserialize, Debug)]
pub struct ClearinghouseState {
    #[serde(rename = "marginSummary")]
    pub margin_summary: MarginSummary,
    
    #[serde(rename = "crossMarginSummary")]
    pub cross_margin_summary: MarginSummary,
    
    #[serde(rename = "crossMaintenanceMarginUsed")]
    pub cross_maintenance_margin_used: String,
    
    pub withdrawable: String,
    
    // The unified array of all active market positions
    #[serde(rename = "assetPositions")]
    pub asset_positions: Vec<AssetPosition>,
    
    pub time: u64,
}

// Global risk parameters calculated natively in memory by the node
#[derive(Serialize, Deserialize, Debug)]
pub struct MarginSummary {
    #[serde(rename = "accountValue")]
    pub account_value: String,      // Total portfolio value (Spot + Perp PnL)
    #[serde(rename = "totalNtlPos")]
    pub total_ntl_pos: String,      // Total notional position size
    #[serde(rename = "totalRawUsd")]
    pub total_raw_usd: String,      // Raw USDC balance
    #[serde(rename = "totalMarginUsed")]
    pub total_margin_used: String,  // Aggregate margin locked
}

// An individual position object within the state
#[derive(Serialize, Deserialize, Debug)]
pub struct AssetPosition {
    pub position: Position,
    #[serde(rename = "type")]
    pub position_type: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Position {
    pub coin: String,         // Asset ticker (e.g., "BTC")
    pub szi: String,          // Size of the position
    pub leverage: Leverage,   
    #[serde(rename = "entryPx")]
    pub entry_px: String,     // Entry Price
    #[serde(rename = "positionValue")]
    pub position_value: String,
    #[serde(rename = "unrealizedPnl")]
    pub unrealized_pnl: String,
    #[serde(rename = "marginUsed")]
    pub margin_used: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Leverage {
    #[serde(rename = "type")]
    pub leverage_type: String,
    pub value: u32,
}

Notice the critical architectural difference here: the MarginSummary fields (account_valuetotal_margin_used) are pre-calculated at the root level of the struct. The developer doesn’t have to write a smart contract to aggregate a user’s collateral across a dozen fragmented liquidity pools. The L1 execution client does the heavy lifting natively on every tick.

Protocol-Level Cross Margin & Portfolio Abstraction This unified architecture unlocks true, protocol-level cross-margin.

Through Hyperliquid’s Portfolio Margin account abstraction, the L1 state machine unifies your spot holdings and perpetual positions into a single global balance. If you bridge USDC to Hyperliquid and buy 1 Spot BTC, the L1 immediately recognizes that asset’s USD value.

How Hyperliquid Agent Keys let bots trade without MetaMask

When you build a sovereign App-Chain, you usually introduce a massive point of friction: the wallet. Historically, if you wanted to trade on other chains, you had to download a new proprietary wallet extension, manage a new seed phrase, and learn a completely new address format.

Hyperliquid bypassed this UX nightmare entirely. Your primary account on Hyperliquid is simply your standard Ethereum address.

But how does a non-EVM execution layer securely verify transactions signed by an Ethereum wallet? And more importantly, how do you solve the high-frequency trading problem, because you certainly cannot click “Sign” in MetaMask a thousand times a second.

The answer lies in two brilliant architectural choices: EIP-712 Native Integration and the Agent Key Architecture.

The L1 wallet (EIP-712 signatures)

Hyperliquid’s L1 natively understands the secp256k1 elliptic curve used by Ethereum. When you interact with the exchange via MetaMask, you aren’t broadcasting a standard Layer 1 Ethereum transaction. Instead, you are signing a structured data payload using the EIP-712 standard.

The HyperCore validator nodes are explicitly programmed to take these EIP-712 signatures, recover the Ethereum public address of the signer, and authenticate the L1 state mutation (like bridging funds or withdrawing).

This EIP-712 address acts as your Root Authority Key. While it delegates trading permissions to temporary Agent Keys (explained shortly) , the HyperCore L1 strictly requires signatures from this Main Wallet for any critical state mutations, such as withdrawing funds or transferring assets, effectively acting as the secure vault for your underlying capital.

📖 Wallet overview and all the possible actions can be found here.

Agent Keys

Using EIP-712 is great for deposits and withdrawals, but it creates a fatal bottleneck for trading. If a bot needs to execute a complex grid-trading strategy, waiting for a user to manually approve a signature prompt for every single order is impossible.

Hyperliquid solves this by allowing users to delegate strict, scoped permissions to a secondary, localized keypair known as an Agent Key.

Here is how the architecture works:

  1. Key Generation: Your bot (or the web UI) generates a fresh, random cryptographic private/public key pair locally in memory. This is the Agent.
  2. The Delegation Action: Your Main L1 Wallet (via MetaMask) signs a specific L1 Action called ApproveAgent. This payload tells the HyperCore state machine: “I authorize this new Agent public key to execute trades on my behalf.”
  3. Local Signing: From that point on, your bot uses the Agent’s private key to sign the actual buy and sell orders locally in microseconds, entirely bypassing MetaMask.

Here is what the raw ApproveAgent action payload looks like when sent to the L1 (Image attached above):

{
  "action": {
    "type": "approveAgent",
    "hyperliquidChain": "Mainnet",
    "signatureChainId": "0xa4b1", // Arbitrum One
    "agentAddress": "0xYourGeneratedAgentPublicKey...",
    "agentName": "0xByteBeetle_GridBot_v1"
  },
  "nonce": 1713563456000,
  "signature": "0xSignatureFromMainL1Wallet..."
}

Example:

you can find here the option to generate wallet agent.

Example of message signing:

Shows the EIP-712 signature

The security boundary

The genius of the Agent Key architecture is its scoped authority.

When the HyperCore L1 receives an order signed by an Agent, it checks the state machine to verify that the Main Wallet delegated authority to it. If verified, the order is executed.

However, Agents are mathematically restricted to trading. If a hacker manages to steal your bot’s Agent private key from your server, the worst they can do is place bad trades. They cannot withdraw your USDC, transfer your spot assets, or change your account settings (Take a look at the note under the API in the first image). The L1 state machine will strictly reject any withdrawal Action signed by an Agent Key. those critical state mutations require a signature directly from the Main L1 Wallet.

Summary

By decoupling the trading engine from a generic VM and baking it directly into the state machine, Hyperliquid solves the latency and state contention problems at the root architectural level. Furthermore, by heavily utilizing EIP-712 and Agent Keys, it manages to provide the blazing speed of a centralized exchange without sacrificing the self-custody and familiar UX of the EVM ecosystem.

We have fundamentally shifted from thinking about smart contract optimizations to thinking about protocol-level memory management and native API actions. On Chainstack, you can deploy private Hyperliquid endpoints in minutes — fully synced, monitored, and backed by a 99.9% uptime SLA — so you can focus on building, not on infrastructure.

FAQ

What is HyperCore in Hyperliquid?

HyperCore is the native trading layer of the Hyperliquid L1 — a purpose-built state machine baked directly into the validator software. It handles order placement, spot transfers, collateral management, and liquidations entirely in memory, enabling 200,000+ orders per second without metering arbitrary bytecode.

What is HyperEVM?

HyperEVM is the Ethereum-compatible execution layer running alongside HyperCore on the same consensus. Developers deploy standard Solidity contracts here using ethers.js, Foundry, or Hardhat. Unlike other EVM chains, HyperEVM contracts can read HyperCore state — prices, positions, margin — in real time via precompiles, without external oracles.

What is the Hyperliquid Clearinghouse?

The Clearinghouse is the unified state tree of HyperCore. It manages every user’s spot holdings and perpetual positions as a single global entity, enabling native cross-margin without bridging or multiple transactions.

What are Agent Keys on Hyperliquid?

Agent Keys are scoped keypairs that your main Ethereum wallet delegates trading permissions to via a single ApproveAgent action. The Agent Key can place and cancel orders locally in microseconds — but cannot withdraw funds or change account settings. Those actions always require the main wallet signature.

How does EIP-712 work on Hyperliquid?

Hyperliquid’s L1 natively understands Ethereum’s secp256k1 curve. When you interact with the exchange, you sign structured data using EIP-712. Validators recover your Ethereum address from the signature and authenticate the state mutation — so any standard Ethereum wallet works as your root authority key with no chain-specific setup.

What is HyperBFT?

HyperBFT is Hyperliquid’s custom consensus mechanism that secures both HyperCore and HyperEVM simultaneously. It provides Byzantine Fault Tolerance optimized for low-latency order book operations, enabling sub-second finality across the entire chain.

Exit mobile version