Architecture

HyperFun Architecture

Overview

HyperFun is a vault system on Hyperliquid that combines:

  • Bonding Curve AMM for token pricing (x*y=k formula)

  • L1 Perpetual Trading for yield generation

  • Automatic Rebalancing between EVM and L1

  • HIP-3 Support for Builder Deployed Perps

All contracts use the UUPS Proxy Pattern for upgradeability.


Code Layout

contracts/src/v3/individual/
├── HyperFunFactory.sol    # Vault factory + global settings
├── HyperFunToken.sol      # Core vault + ERC20 token + AMM
└── HyperFunTrading.sol    # L1 trading module

Contract Architecture


Core Responsibilities

HyperFunFactory

Role: Vault deployment, global configuration, upgrade authority

Function
Description

createVault()

Deploy new Token + Trading proxies

createVaultAdvanced()

Deploy with custom BC params (Owner only)

setGlobal*()

Configure global settings

setImplementations()

Update implementation contracts

setGraduationTiers()

Configure BC/NAV virtual tiers

upgradeToAndCall()

Upgrade factory itself

Global Settings:

  • Trading fee (default 1%)

  • Min deposit (default 5 USDC)

  • Rebalance thresholds (48%-52%)

  • Reserve ratio (50%)

  • Exit fee tiers (time-based decay)

  • Graduation tiers (BC Virtual scaling)

  • NAV Virtual parameters

  • Builder fee settings

  • Max BC ratio (price divergence protection)


HyperFunToken (VaultCore)

Role: Token accounting, NAV, buy/sell, fees

Category
Functions

ERC20

transfer, balanceOf, totalSupply

Pricing

getNAV, getSmoothedNAV, getBuyPrice, getSellPrice

Trading

buy, sell, claimSell, deposit

View

getTotalAssets, getAvailableLiquidity, calculateTokensOut, calculateUsdcOut

L1

executeL1Action, depositToL1, initializeL1

Admin

approveBuilderFee, setPaused, setTradingModule

State:


HyperFunTrading

Role: L1 trading operations, fund transfers, rebalancing

Category
Functions

Standard Orders

executeMarketOrder, executeLimitOrder, executeLimitOrderRaw

Close

closePositionAdvanced, executeCloseOrderAdvanced

Batch

batchLimitOrders, cancelOrder

HIP-3 (V46)

executeOrderBuilder, closePositionBuilder

Transfers

transferToPerp, transferFromPerp, sweepToSpot, forceReturnToSpot

Rebalance

autoRebalance, checkReserve

API Wallet

addApiWallet, removeApiWallet, renewApiWallet, getApiWalletStatus

View

getL1Position, getL1PositionFull, getL1SpotBalance, getL1AccountValue

Admin

withdrawPerpToEVM, withdrawAllPerpToEVM, refillReserve

State:


UUPS Proxy Pattern

How It Works

Implementation Slots

Upgrade Authority

Contract
Who Can Upgrade

Factory

Factory Owner

Token (Vault)

Factory Owner

Trading

Factory Owner

Security: Only factory owner can upgrade implementations. This protects investors from malicious leader upgrades.


Deployment Flow

1. Deploy Factory

2. Create Vault

Steps executed:

  1. Collect creation fee (if set)

  2. Collect L1 init fee (1 USDC)

  3. Deploy Trading proxy (ERC1967)

  4. Deploy Token proxy (ERC1967)

  5. Initialize Trading with Token reference

  6. Initialize Token with Trading reference

  7. Approve builder fee (if configured)

  8. Set admin to factory owner

  9. Initialize L1 account (deposit 1 USDC)

  10. Register vault in factory


Fund Flow

Buy Flow

Sell Flow (Normal)

Sell Flow (Pending Sell)

Rebalance Flow


L1 Communication

CoreWriter Actions

Action Encoding Example

Precompiles (Read L1 State)

Address
Name
Returns

0x800

PRECOMPILE_PERP_POSITION

(int64 szi, uint64 entryNtl, int64 isolatedRawUsd, uint32 leverage, bool isIsolated)

0x801

PRECOMPILE_SPOT

(uint256 total, uint256 hold, uint256 entryNtl) in 8 decimals

0x803

PRECOMPILE_WITHDRAWABLE

uint64 withdrawable from perp

0x807

PRECOMPILE_ORACLE

uint64 oracle price

0x80A

PRECOMPILE_PERP_ASSET_INFO

(string name, uint32 marginTableId, uint32 szDecimals, uint32 maxLeverage, bool onlyIsolated)

0x80F

PRECOMPILE_ACCOUNT_MARGIN_SUMMARY

(int64 accountValue, uint64 marginUsed, uint64 ntlPos, int64 rawUsd)

Note: Precompiles don't support HIP-3 assets (index >= 100000). Use executeOrderBuilder() with params from API.


HIP-3 Support (V46)

What is HIP-3?

HIP-3 (Builder Deployed Perps) allows anyone to create perpetual markets on Hyperliquid. These have asset indices >= 100000.

Why Special Functions?

EVM precompiles (0x807, 0x80A) don't return data for HIP-3 assets. The caller must provide:

  • szDecimals - Position size precision

  • maxLeverage - Maximum leverage allowed

  • price - Limit price (no oracle fallback)

HIP-3 Functions

Standard vs HIP-3 Comparison

Feature
Standard (< 100000)
HIP-3 (>= 100000)

Oracle Price

Precompile 0x807

Must provide

szDecimals

Precompile 0x80A

Must provide

maxLeverage

Precompile 0x80A

Must provide

Open Function

executeMarketOrder()

executeOrderBuilder()

Close Function

closePositionAdvanced()

closePositionBuilder()


Security Model

Roles

Role
Who
Permissions

Factory Owner

Platform admin

Upgrade all contracts, global settings, emergency functions

Vault Admin

Factory owner

Pause vault, change trading module

Leader

Vault creator

Execute trades, add API wallets, set metadata

API Wallet

Authorized by leader

Execute trades (with expiration 60-180 days)

User

Anyone

Buy, sell, claim pending sells

Protections

Protection
Description

Upgrade Lock

Only factory owner can upgrade (not leader)

Reentrancy Guard

All state-changing functions

Slippage Protection

minTokensOut / minUsdcOut parameters

Price Bounds

Max premium/discount from NAV

TWAP NAV (V40)

Smoothed NAV with half-life decay

BC Ratio Cap (V39)

Prevents extreme price divergence

API Wallet Expiry (V39)

60-180 days, auto-expire

Pending Sell Reserve

USDC reserved for claims

Entry NAV Inheritance

Prevents performance fee gaming via transfers

Order Nonce (V41)

Unique cloid prevents duplicate orders

Access Control Modifiers


Contract Addresses

System Contracts

Contract
Address

USDC

0xb88339CB7199b77E23DB6E890353E22632Ba630f

CoreDepositWallet

0x6B9E773128f453f5c2C60935Ee2DE2CBc5390A24

CoreWriter

0x3333333333333333333333333333333333333333

USDC L1 System

0x2000000000000000000000000000000000000000

Production Factory

Testing Factory


Global Settings Reference

Factory Defaults

Constants


Version History

Version
Changes

V34

BC Virtual minimum floor (globalBcVirtualMinimumBps)

V35

Dynamic NAV Virtual (mode 0/1/2)

V36

Auto-dynamic NAV Virtual (interpolation by vault size)

V37

Graduation Tier System for BC/NAV Virtual

V38

Progressive squared effect decay (squaredRatioBps), L1 init fee

V39

API Wallet expiration (60-180 days), BC ratio cap/floor, slippage protection

V40

TWAP NAV smoothing (half-life decay for price protection)

V41

Order nonce for unique cloid (prevents duplicate orders)

V42

Skip rebalance on pending sell, L1 precision buffer (0.5%)

V43

NAV Virtual minimum floor (1000 tokens), pending sell in rebalance calc

V44

Exit fee stays in vault (not transferred to recipient)

V45

Uses marginUsed from Account Margin Summary precompile (0x80F)

V46

HIP-3 Builder Perp support (executeOrderBuilder, closePositionBuilder)

V47

Entry NAV fix (use pre-transfer NAV for accurate performance fee)


File Dependencies

Last updated