> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tide.ag/llms.txt
> Use this file to discover all available pages before exploring further.

# User Flow Documentation

> Complete guide for setting up and using Lighter DEX integration with HyperDEX

## Overview

This document explains the complete user flow for integrating with Lighter DEX through HyperDEX. The process involves creating a server wallet, registering with exchanges, depositing funds, and executing trades.

<Warning>
  **Important for Lighter DEX Users**: Before using Lighter DEX through HyperDEX, you must:

  1. Create an account on [Lighter DEX](https://app.lighter.xyz)
  2. Deposit funds into your Lighter account
  3. Generate API keys from the Lighter platform
  4. Use those API keys in HyperDEX API calls
</Warning>

***

## Complete User Flow Diagrams

### Aster DEX Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant HyperDEX API
    participant Dynamic Labs
    participant Aster DEX
    participant BSC Blockchain

    Note over User,BSC Blockchain: Step 1: Wallet Creation
    User->>HyperDEX API: POST /api/wallets {userId}
    HyperDEX API->>Dynamic Labs: Create MPC Wallet
    Dynamic Labs-->>HyperDEX API: Wallet Created (address, walletId)
    HyperDEX API-->>User: Return wallet details

    Note over User,BSC Blockchain: Step 2: Register API Keys
    User->>HyperDEX API: POST /api/trading/aster/apikey
    HyperDEX API->>HyperDEX API: Sign Registration Message
    HyperDEX API->>Aster DEX: Register Wallet & Signature
    Aster DEX-->>HyperDEX API: API Credentials
    HyperDEX API-->>User: signerAddress & createdAt

    Note over User,BSC Blockchain: Step 3: Fund Server Wallet
    User->>BSC Blockchain: Transfer USDT + BNB to server wallet
    BSC Blockchain-->>User: Transaction Confirmed

    Note over User,BSC Blockchain: Step 4: Deposit to Aster
    User->>HyperDEX API: POST /api/trading/aster/deposit
    HyperDEX API->>BSC Blockchain: Approve USDT (if needed)
    BSC Blockchain-->>HyperDEX API: Approval Confirmed
    HyperDEX API->>BSC Blockchain: Deposit Transaction
    BSC Blockchain-->>Aster DEX: Funds Deposited to Spot
    HyperDEX API->>Aster DEX: Transfer Spot to Perp (optional)
    Aster DEX-->>User: Balance Updated

    Note over User,BSC Blockchain: Step 5: Trading Operations
    User->>HyperDEX API: POST /api/trading/aster/orders
    HyperDEX API->>Aster DEX: Execute Trade with Signature
    Aster DEX-->>HyperDEX API: Order Confirmation
    HyperDEX API-->>User: Trade Result

    Note over User,BSC Blockchain: Step 6: Withdraw Funds
    User->>HyperDEX API: POST /api/trading/aster/withdraw
    HyperDEX API->>Aster DEX: Sign & Submit Withdrawal Request
    Aster DEX->>BSC Blockchain: Process Withdrawal Transaction
    BSC Blockchain-->>User: USDT Received
```

### Hyperliquid DEX Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant HyperDEX API
    participant Dynamic Labs
    participant Hyperliquid DEX
    participant Arbitrum Blockchain

    Note over User,Arbitrum Blockchain: Step 1: Wallet Creation
    User->>HyperDEX API: POST /api/wallets {userId}
    HyperDEX API->>Dynamic Labs: Create MPC Wallet
    Dynamic Labs-->>HyperDEX API: Wallet Created (address, walletId)
    HyperDEX API-->>User: Return wallet details

    Note over User,Arbitrum Blockchain: Step 2: Register API Keys
    User->>HyperDEX API: POST /api/trading/hyperliquid/apikey
    HyperDEX API->>HyperDEX API: Generate API Wallet & Sign
    HyperDEX API->>Hyperliquid DEX: Register API Wallet
    Hyperliquid DEX-->>HyperDEX API: Registration Confirmed
    HyperDEX API-->>User: apiWalletAddress, apiPrivateKey, expiry

    Note over User,Arbitrum Blockchain: Step 3: Fund Server Wallet
    User->>Arbitrum Blockchain: Transfer USDC + ETH to server wallet
    Arbitrum Blockchain-->>User: Transaction Confirmed

    Note over User,Arbitrum Blockchain: Step 4: Deposit to Hyperliquid
    User->>HyperDEX API: POST /api/trading/hyperliquid/deposit
    HyperDEX API->>Arbitrum Blockchain: Sign Deposit Transaction
    Arbitrum Blockchain-->>Hyperliquid DEX: Funds Deposited
    Hyperliquid DEX-->>User: Balance Updated

    Note over User,Arbitrum Blockchain: Step 5: Trading Operations
    User->>HyperDEX API: POST /api/trading/hyperliquid/orders
    HyperDEX API->>Hyperliquid DEX: Execute Trade with API Wallet
    Hyperliquid DEX-->>HyperDEX API: Order Confirmation
    HyperDEX API-->>User: Trade Result

    Note over User,Arbitrum Blockchain: Step 6: Withdraw Funds
    User->>HyperDEX API: POST /api/trading/hyperliquid/withdraw
    HyperDEX API->>Hyperliquid DEX: Sign & Submit Withdrawal
    Hyperliquid DEX->>Arbitrum Blockchain: Process Withdrawal
    Arbitrum Blockchain-->>User: USDC Received
```

### Lighter DEX Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant HyperDEX API
    participant Lighter DEX
    participant Arbitrum Blockchain

    Note over User,Arbitrum Blockchain: Step 1: Setup Lighter Account
    User->>Lighter DEX: 1. Create Account on app.lighter.xyz
    User->>Lighter DEX: 2. Connect Personal Wallet
    User->>Arbitrum Blockchain: 3. Deposit USDC to Lighter
    Arbitrum Blockchain-->>Lighter DEX: Funds Deposited
    User->>Lighter DEX: 4. Generate API Keys in Dashboard
    Lighter DEX-->>User: apiKeyPrivateKey, apiKeyIndex, accountIndex

    Note over User,Arbitrum Blockchain: Step 2: Trading via HyperDEX
    User->>HyperDEX API: POST /api/trading/lighter/orders?apiKeyPrivateKey=xxx&apiKeyIndex=5&accountIndex=316225
    HyperDEX API->>Lighter DEX: Execute Trade with User's API Credentials
    Lighter DEX-->>HyperDEX API: Order Confirmation
    HyperDEX API-->>User: Trade Result

    Note over User,Arbitrum Blockchain: Step 3: Withdraw Funds
    User->>Lighter DEX: Withdraw via app.lighter.xyz
    Lighter DEX->>Arbitrum Blockchain: Process Withdrawal
    Arbitrum Blockchain-->>User: USDC Received to Personal Wallet
```

### Avantis DEX Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Frontend
    participant Tide API
    participant Avantis Contracts
    participant Base Blockchain

    Note over User,Base Blockchain: Step 1: Fund Wallet on Base
    User->>Base Blockchain: Transfer USDC + ETH to wallet
    Base Blockchain-->>User: Transaction Confirmed

    Note over User,Base Blockchain: Step 2: Query Data via Tide Backend
    User->>Tide API: GET /api/trading/positions/all/{address}
    Tide API-->>User: Avantis positions, orders, balances
    User->>Tide API: GET /api/trading/avantis/orders
    Tide API-->>User: Open limit orders
    User->>Tide API: GET /api/balances/{address}
    Tide API-->>User: USDC balance & available balance

    Note over User,Base Blockchain: Step 3: Execute Trades (Client-Side)
    User->>Frontend: Open position (useAvantisTrade hook)
    Frontend->>Frontend: Build transaction & sign with wallet
    Frontend->>Avantis Contracts: Submit signed transaction
    Avantis Contracts->>Base Blockchain: Execute on-chain
    Base Blockchain-->>Frontend: Transaction confirmed (txHash)
    Frontend-->>User: { txHash, symbol, direction, size, leverage }

    Note over User,Base Blockchain: Step 4: Close Position (Client-Side)
    User->>Frontend: Close position (useAvantisTrade hook)
    Frontend->>Frontend: Read initialPosToken from TradingStorage
    Frontend->>Avantis Contracts: Submit close transaction
    Avantis Contracts->>Base Blockchain: Execute on-chain
    Base Blockchain-->>Frontend: Transaction confirmed (txHash)
    Frontend-->>User: txHash
```

<Note>
  **Avantis Architecture**: Unlike other exchanges, Avantis uses a split architecture. The Tide backend provides **data only** (positions, orders, history, balances). All trade **execution** happens client-side via wallet signing on the Base network through the `useAvantisTrade` React hook.
</Note>

***

## Step-by-Step Flow

### Step 1: Create Server Wallet

Create a server-side wallet secured with MPC (Multi-Party Computation) key management through Dynamic Labs.

**Endpoint:** `POST /api/wallets`

**Request:**

```json theme={null}
{
  "userId": "user_123"
}
```

**What Happens:**

* Dynamic Labs creates a wallet with 2-of-2 MPC threshold scheme
* Wallet includes: private key shares, public key, and address
* Wallet is stored securely in the database

**Response:**

```json theme={null}
{
  "success": true,
  "userId": "user_123",
  "address": "0x173404aAAa4d6539e2C7dbcC1931Cf41b3A3D5c7",
  "walletId": "29dd4dc0-1ff9-4df6-a19f-936f997cbc5a",
  "publicKey": "04090ce18936a64a24c48624d5734edf96d33a5f3d79bb014f27ebfa2197a813cfc46009ac278f4de56afc3e48733d1adf1a6cf804e6b20ddf55a9f5d4f651104a"
}
```

**Key Information to Store:**

* `userId` - User identifier for wallet lookup
* `address` - Wallet address (0x...) needed for deposits & transactions
* `walletId` - Wallet UUID needed for API registration & signing
* `publicKey` - Public key for verification

***

### Step 2: Register API Keys with Exchanges

After wallet creation, register the wallet with exchanges to get API credentials for trading.

#### Aster Exchange

**Endpoint:** `POST /api/trading/aster/apikey`

**Request:**

```json theme={null}
{
  "walletIdOrAddress": "29dd4dc0-1ff9-4df6-a19f-936f997cbc5a"
}
```

**Can use any of these identifiers:**

* `userId`: "user\_123"
* `walletId`: "29dd4dc0-1ff9-4df6-a19f-936f997cbc5a"
* `address`: "0x173404aAAa4d6539e2C7dbcC1931Cf41b3A3D5c7"

**Response:**

```json theme={null}
{
  "success": true,
  "message": "API key generated successfully",
  "data": {
    "signerAddress": "0x173404aAAa4d6539e2C7dbcC1931Cf41b3A3D5c7",
    "createdAt": "2025-11-27T02:00:00Z"
  }
}
```

#### Hyperliquid Exchange

**Endpoint:** `POST /api/trading/hyperliquid/apikey`

**Request:**

```json theme={null}
{
  "walletIdOrAddress": "user_123"
}
```

**Response:**

```json theme={null}
{
  "success": true,
  "data": {
    "apiWalletAddress": "0xa95B2862DF3896cA5c284725D71Ab373e78de96b",
    "apiPrivateKey": "0x01c6baa2be13089ff710c2f037fdb7aec2fdc5faf2e12afe6ff99cc8d5fe7c5a",
    "mainWalletAddress": "0x07943f0f79097572451601e768c329a2765f2ea2",
    "expiryTimestamp": 1779903620779
  }
}
```

#### Lighter Exchange

<Warning>
  **Lighter DEX Requirement**: You do NOT need to register API keys through HyperDEX for Lighter. Instead:

  1. Create an account on [Lighter DEX](https://app.lighter.xyz)
  2. Deposit funds directly on Lighter
  3. Generate API keys from your Lighter account dashboard
  4. Provide these credentials as query parameters when making order requests
</Warning>

***

### Step 3: Fund the Server Wallet

Before depositing to exchanges, your server wallet must have:

1. **USDT** - Trading token on BSC
2. **BNB** - Native currency for gas fees

**How to Fund:**

```
User's Personal Wallet
    ↓ (transfer USDT + BNB)
Server Wallet (0x173404aAAa4d6539e2C7dbcC1931Cf41b3A3D5c7)
```

***

### Step 4: Deposit to Exchange

**Endpoint:** `POST /api/trading/:exchange/deposit`

#### Aster Deposit Example

**Request:**

```json theme={null}
{
  "walletIdOrAddress": "user_123",
  "tokenSymbol": "USDT",
  "amount": "100",
  "broker": 1000,
  "network": "bnb"
}
```

**Parameters:**

| Field               | Type   | Required | Description                                    |
| ------------------- | ------ | -------- | ---------------------------------------------- |
| `walletIdOrAddress` | string | Yes      | Can be userId, walletId, or address            |
| `tokenSymbol`       | string | Yes      | Token to deposit (e.g., "USDT")                |
| `amount`            | string | Yes      | Amount in token units (e.g., "100" = 100 USDT) |
| `broker`            | number | Yes      | Broker ID (default: 1000)                      |
| `network`           | string | Yes      | Network ("ethereum", "arbitrum", "bnb")        |

**What Happens:**

1. Check Balance - Verify server wallet has sufficient USDT and BNB for gas
2. Approve Token (if needed) - Sign approval transaction and broadcast
3. Deposit Transaction - Sign deposit transaction to exchange contract
4. Internal Transfer (optional) - Transfer from Spot to Futures/Perp account

**Response:**

```json theme={null}
{
  "success": true,
  "data": {
    "txHash": "0x1234abcd...",
    "txUrl": "https://bscscan.com/tx/0x1234abcd...",
    "amount": "100",
    "token": "USDT",
    "network": "bsc",
    "decimals": 6,
    "blockNumber": "12345678"
  }
}
```

#### Transfer Between Spot and Perp Accounts

**Endpoint:** `POST /api/aster/wallet/transfer`

**Request:**

```json theme={null}
{
  "walletId": "29dd4dc0-1ff9-4df6-a19f-936f997cbc5a",
  "amount": "50",
  "asset": "USDT",
  "clientTranId": "transfer_001",
  "kindType": "SPOT_FUTURE"
}
```

**Direction Options:**

* `SPOT_FUTURE` - Transfer from Spot → Futures
* `FUTURE_SPOT` - Transfer from Futures → Spot

***

### Step 5: Trading Operations

#### Aster Trading

**Endpoint:** `POST /api/trading/aster/orders`

**Headers:**

```
x-wallet-id: ee337309-3e77-4278-b21a-4681468168ba
```

**Request:**

```json theme={null}
{
  "userId": "0x07943f0f79097572451601e768c329a2765f2ea2",
  "symbol": "BTCUSDT",
  "side": "BUY",
  "type": "MARKET",
  "quantity": "0.1",
  "reduceOnly": true
}
```

#### Hyperliquid Trading

**Endpoint:** `POST /api/trading/hyperliquid/orders`

**Request:**

```json theme={null}
{
  "userId": "ee337309-3e77-4278-b21a-4681468168ba",
  "symbol": "BTC-PERP",
  "side": "BUY",
  "type": "MARKET",
  "quantity": "0.1",
  "price": "1",
  "reduceOnly": true
}
```

#### Lighter Trading

<Note>
  **Lighter DEX Trading**: Lighter requires API credentials as query parameters in the order request.
</Note>

**Endpoint:** `POST /api/trading/lighter/orders?apiKeyPrivateKey=<key>&apiKeyIndex=<index>&accountIndex=<account>`

**Query Parameters:**

* `apiKeyPrivateKey` - Your Lighter API key private key (hex format)
* `apiKeyIndex` - API key index from Lighter
* `accountIndex` - Your Lighter account index

**Request:**

```json theme={null}
{
  "userId": "0x07943f0f79097572451601e768c329a2765f2ea2",
  "symbol": "USDC",
  "side": "BUY",
  "type": "MARKET",
  "quantity": "1.1",
  "price": "1",
  "reduceOnly": true
}
```

***

### Step 6: Withdraw from Exchange

**Endpoint:** `POST /api/trading/:exchange/withdraw`

#### Aster Withdrawal

**Request:**

```json theme={null}
{
  "walletAddress": "0x07943f0f79097572451601e768c329a2765f2ea2",
  "chainId": 56,
  "asset": "USDT",
  "amount": "50",
  "broker": 1000,
  "receiver": "0x07943f0f79097572451601e768c329a2765f2ea2",
  "accountType": "perp"
}
```

**Important:** The receiver address should match the wallet address for signature verification.

**Response:**

```json theme={null}
{
  "success": true,
  "withdrawalId": "4c93dfe1-8c62-40ae-93d7-f02a999ab2f7",
  "status": "submitted",
  "timestamp": 1698840000000
}
```

#### Hyperliquid Withdrawal

**Request:**

```json theme={null}
{
  "walletIdOrAddress": "0x07943f0f79097572451601e768c329a2765f2ea2",
  "destination": "0x07943f0f79097572451601e768c329a2765f2ea2",
  "amount": "5",
  "feeBuffer": "1.1",
  "chainId": 42161
}
```

**Response:**

```json theme={null}
{
  "success": true,
  "withdrawalId": 9183374,
  "status": "accepted",
  "network": "arbitrum",
  "timestamp": 1698840000000
}
```

***

## Summary

The complete flow for using HyperDEX with exchange integrations:

1. **Create Wallet** - Generate MPC-secured server wallet via Dynamic Labs
2. **Register API Keys** - Link wallet to exchanges (Aster, Hyperliquid)
3. **Fund Wallet** - Transfer USDT and gas tokens to server wallet
4. **Deposit** - Move funds from wallet to exchange accounts
5. **Trade** - Execute orders across multiple exchanges
6. **Withdraw** - Move funds back to server wallet or personal wallet

For **Avantis**, the flow is simpler: fund your wallet with USDC on Base, then use the Tide backend for data queries and the frontend `useAvantisTrade` hook for on-chain trade execution. No server wallet or API key registration is required.

<Tip>
  For Lighter DEX specifically, remember to create your account and generate API keys directly on their platform before using HyperDEX APIs.
</Tip>
