# 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

{% code fullWidth="true" %}

```
┌─────────────────────────────────────────────────────────────────────┐
│                         HyperFunFactory                             │
│                    (UUPS Proxy - Upgradeable)                       │
│                                                                     │
│  • Deploy new vaults (createVault)                                  │
│  • Global settings (fees, tiers, limits)                            │
│  • Upgrade authority for all vaults                                 │
│  • Builder fee management                                           │
└─────────────────────────────────────────────────────────────────────┘
                                │
                                │ creates
                                ▼
┌─────────────────────────────────────────────────────────────────────┐
│                    Per-Vault Architecture                           │
│                                                                     │
│  ┌──────────────────────────┐    ┌──────────────────────────┐       │
│  │     HyperFunToken        │    │    HyperFunTrading       │       │
│  │   (UUPS Proxy - Core)    │◄───│   (UUPS Proxy - L1)      │       │
│  │                          │    │                          │       │
│  │  • ERC20 vault token     │    │  • Perp order execution  │       │
│  │  • NAV calculation       │    │  • Spot ↔ Perp transfers │       │
│  │  • Buy/Sell (AMM)        │    │  • Auto-rebalance        │       │
│  │  • Pending sells         │    │  • API wallet auth       │       │
│  │  • Fee collection        │    │  • Position management   │       │
│  │  • L1 action execution   │    │  • HIP-3 Builder perps   │       │
│  └──────────────────────────┘    └──────────────────────────┘       │
│              │                              │                       │
│              │         executeL1Action      │                       │
│              └──────────────────────────────┘                       │
│                              │                                      │
└──────────────────────────────┼──────────────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────────────┐
│                      Hyperliquid L1                                 │
│                                                                     │
│  ┌─────────────┐  ┌─────────────┐  ┌───────────────┐                │
│  │  L1 Spot    │  │  L1 Perp    │  │  Precompiles  │                │
│  │   USDC      │  │  Positions  │  │  (Oracles)    │                │
│  └─────────────┘  └─────────────┘  └───────────────┘                │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

{% endcode %}

***

### 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:**

```solidity
// Core
address public leader;
address public admin;
address public tradingModule;
address public factory;

// Bonding Curve
uint256 public virtualBase;
uint256 public virtualTokens;
uint256 public initialAssets;

// Pending Sells (PS)
mapping(address => PSSell) public pendingSells;
uint256 public totalPSUsdc;

// Tracking
uint256 public totalDeposits;
uint256 public totalVolume;
mapping(address => UserPurchaseInfo) public userPurchaseInfo;  // Exit fee
mapping(address => EntryRecord) public entryRecords;           // Performance fee
mapping(address => DepositRecord) public depositRecords;       // Legacy

// TWAP (V40)
uint256 public twapNav;
uint256 public twapNavTime;
uint256 public twapMaxChangePerMin;  // Half-life in seconds
```

***

#### 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:**

```solidity
address public vault;
address public factory;

// API Wallets (V39)
struct ApiWalletInfo {
    bool active;
    uint256 expiresAt;    // Unix timestamp
    string name;
}
mapping(address => ApiWalletInfo) public apiWalletInfo;
mapping(address => bool) public apiWallets;  // Legacy

// Order tracking (V41)
uint128 public orderNonce;

// Constants
uint256 public constant MIN_API_WALLET_DURATION = 60 days;
uint256 public constant MAX_API_WALLET_DURATION = 180 days;
```

***

### UUPS Proxy Pattern

#### How It Works

```
┌─────────────────┐         ┌─────────────────┐
│   Proxy         │         │ Implementation  │
│   (Storage)     │────────►│ (Logic)         │
│                 │         │                 │
│  • Holds state  │         │  • Pure logic   │
│  • Delegates    │         │  • No state     │
│    all calls    │         │  • Upgradeable  │
└─────────────────┘         └─────────────────┘
```

#### Implementation Slots

```solidity
// ERC1967 implementation slot
bytes32 constant IMPL_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
```

#### 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.

```solidity
function _authorizeUpgrade(address) internal override {
    require(msg.sender == IHyperFunFactory(factory).owner(), "Only factory owner");
}
```

***

### Deployment Flow

#### 1. Deploy Factory

```
Factory Impl ──► Factory Proxy (ERC1967)
                     │
                     ▼
              Initialize:
              • Set owner
              • Set implementations
              • Set global settings
              • Set default BC params
              • Set exit fee tiers
```

#### 2. Create Vault

```solidity
factory.createVault(
    "Vault Name",        // ERC20 name
    "SYMBOL",            // ERC20 symbol
    performanceFeeBps    // Performance fee (max 3000 = 30%)
)
```

**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

```
User USDC ──► Token (EVM) ──► L1 Spot ──► L1 Perp (via Trading)
                  │
                  ▼
            Mint vault tokens
            to buyer
```

#### Sell Flow (Normal)

```
User tokens ──► Token (burn) ──► User receives USDC from EVM
```

#### Sell Flow (Pending Sell)

```
User tokens ──► Token (burn) ──► Pending Sell created
                                       │
                                       ▼
                              SPOT_SEND (L1 → EVM)
                                       │
                                       ▼
                              User calls claimSell()
                                       │
                                       ▼
                              User receives USDC
```

#### Rebalance Flow

```
              ┌─────────────────────────────────────┐
              │         Auto-Rebalance              │
              │                                     │
              │  Target: 50% EVM / 50% L1           │
              │  Trigger: < 48% or > 52%            │
              └─────────────────────────────────────┘
                              │
           ┌──────────────────┴──────────────────┐
           │                                     │
           ▼                                     ▼
    EVM > 52%                              EVM < 48%
    Deposit to L1                          SPOT_SEND from L1
```

***

### L1 Communication

#### CoreWriter Actions

```solidity
ICoreWriter constant CORE_WRITER = ICoreWriter(0x3333333333333333333333333333333333333333);

// Action IDs
uint24 constant ACTION_LIMIT_ORDER = 1;          // Place perp order
uint24 constant ACTION_SPOT_SEND = 6;            // L1 Spot → EVM
uint24 constant ACTION_USD_CLASS_TRANSFER = 7;   // Spot ↔ Perp
uint24 constant ACTION_ADD_API_WALLET = 9;       // Register API wallet on L1
uint24 constant ACTION_CANCEL_BY_OID = 10;       // Cancel order by oid
uint24 constant ACTION_APPROVE_BUILDER_FEE = 12; // Approve builder fee
```

#### Action Encoding Example

```solidity
// Transfer from Spot to Perp
bytes memory action = abi.encodePacked(
    uint8(1),                           // Version
    ACTION_USD_CLASS_TRANSFER,          // Action ID (7)
    abi.encode(amount, true)            // Payload (amount, toPerp)
);
CORE_WRITER.sendRawAction(action);

// Place order with unique cloid
orderNonce++;
bytes memory orderAction = abi.encodePacked(
    uint8(1),
    ACTION_LIMIT_ORDER,
    abi.encode(asset, isBuy, price, size, reduceOnly, tif, orderNonce)
);
```

#### 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

```solidity
// Open position on HIP-3 perp
function executeOrderBuilder(
    uint32 asset,           // e.g., 110003 for xyz:GOLD
    bool isBuy,
    uint64 size,            // 1e8 format
    uint64 price,           // 1e8 format
    uint32 szDecimals,      // From API
    uint32 maxLeverage,     // From API
    bool isLimit            // true=GTC, false=IOC
) external;

// Close position on HIP-3 perp
function closePositionBuilder(
    uint32 asset,
    bool isBuy,             // Opposite of position direction
    uint64 size,
    uint64 price,
    uint32 szDecimals
) external;
```

#### 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

```solidity
modifier onlyAdmin() {
    require(msg.sender == admin, "!Admin");
    _;
}

modifier onlyLeader() {
    require(msg.sender == leader, "!Leader");
    _;
}

modifier onlyVaultOrLeader() {
    require(
        msg.sender == vault ||
        msg.sender == IHyperFunToken(vault).leader() ||
        _isApiWalletValid(msg.sender),
        "Not authorized"
    );
    _;
}

modifier onlyFactoryOwner() {
    require(
        factory != address(0) &&
        (msg.sender == factory || msg.sender == IHyperFunFactory(factory).owner()),
        "!FO"
    );
    _;
}

modifier onlyTradingModule() {
    require(msg.sender == tradingModule, "!TM");
    _;
}
```

***

### Contract Addresses

#### System Contracts

| Contract          | Address                                      |
| ----------------- | -------------------------------------------- |
| USDC              | `0xb88339CB7199b77E23DB6E890353E22632Ba630f` |
| CoreDepositWallet | `0x6B9E773128f453f5c2C60935Ee2DE2CBc5390A24` |
| CoreWriter        | `0x3333333333333333333333333333333333333333` |
| USDC L1 System    | `0x2000000000000000000000000000000000000000` |

#### Production Factory

```
Factory Proxy: 0xeE7dB1582e46c054792AdD4bb52b8D4D6ab45555
Token Impl:    factory.coreImplementation()
Trading Impl:  factory.tradingImplementation()
```

#### Testing Factory

```
Factory Proxy: 0xEA0c5fF39f615d5428C8A5832c235dCb86F01F9A
Token Impl:    factory.coreImplementation()
Trading Impl:  factory.tradingImplementation()
```

***

### Global Settings Reference

#### Factory Defaults

```solidity
// Trading
globalTradingFeeBps = 100;              // 1%
globalMinDepositUsdc = 5 * 1e6;         // 5 USDC
globalMaxBuyBps = 100;                  // 1% of vault per tx

// Price Limits
globalMaxPremiumBps = 10000;            // 100%
globalMaxDiscountBps = 5000;            // 50%

// Rebalance
globalRebalanceLowBps = 4800;           // 48%
globalRebalanceHighBps = 5200;          // 52%
globalReserveRatioBps = 5000;           // 50%
globalMinReserveRatioBps = 3000;        // 30%

// Bonding Curve
defaultBcVirtualBase = 2_000_000 * 1e18;
defaultBcVirtualTokens = 2_000_000 * 1e18;
defaultInitialAssets = 100_000 * 1e18;
globalBcVirtualMinimumBps = 500;        // 5%
globalMaxBcRatioBps = 0;                // Disabled (0) or 1.8x-5x

// Exit Fee Tiers (default)
// <7 days:   15%
// 7-30 days:  8%
// 30-90 days: 3%
// >90 days:   0%
```

#### Constants

```solidity
uint256 constant MAX_PERFORMANCE_FEE = 3000;  // 30%
uint256 constant MAX_EXIT_FEE = 5000;         // 50%
uint256 constant L1_INIT_FEE = 1000000;       // 1 USDC
uint256 constant BPS = 10000;
uint256 constant PRECISION = 1e18;

// API Wallet
uint256 constant MIN_API_WALLET_DURATION = 60 days;
uint256 constant MAX_API_WALLET_DURATION = 180 days;

// TIF (Time In Force)
uint8 constant TIF_GTC = 2;  // Good Till Cancel
uint8 constant TIF_IOC = 3;  // Immediate Or Cancel
```

***

### 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

```
HyperFunFactory.sol
    └── imports: ERC1967Proxy, Initializable, UUPSUpgradeable, OwnableUpgradeable, IERC20
    └── interfaces: IHyperFunToken, IHyperFunTrading

HyperFunToken.sol
    └── imports: Initializable, UUPSUpgradeable, OwnableUpgradeable,
                 ReentrancyGuardUpgradeable, ERC20Upgradeable, IERC20
    └── interfaces: ICoreWriter, ICoreDepositWallet, IHyperFunTrading, IHyperFunFactory

HyperFunTrading.sol
    └── imports: UUPSUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable
    └── interfaces: ICoreWriter, IHyperFunToken, IHyperFunFactory, IERC20
```


---

# Agent Instructions: 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:

```
GET https://hyper-fun.gitbook.io/hypers.fun/smart-contracts/architecture.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
