> 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/hertzflow-sdk.md).

# HertzFlow SDK

## About

The HertzFlow SDK is a TypeScript-based SDK developed for interacting with HertzFlow protocol. It provides a comprehensive set of tools and utilities for building decentralized trading applications, managing positions, executing orders, and monitoring real-time market data.

### Installation

#### Using npm

```bash
npm install @hertzflow/sdk-v2
```

#### Using yarn

```bash
yarn add @hertzflow/sdk-v2
```

#### Using pnpm

```bash
pnpm add @hertzflow/sdk-v2
```

## Getting Started

#### Basic Configuration

```typescript
import { HertzFlowSDK } from "@hertzflow/sdk-v2";

const sdk = new HertzFlowSDK({
  chainId: 97,                                       // BSC Testnet
  rpcUrl: "https://data-seed-prebsc-1-s1.binance.org:8545",
  oracleUrl: "https://oracle.hertzflow.com",
  statsUrl: "https://stats.hertzflow.com",
  account: "0xYourWalletAddress",
});
```

#### With Custom Viem Clients

```typescript
import { HertzFlowSDK } from "@hertzflow/sdk-v2";
import { createPublicClient, createWalletClient, http } from "viem";
import { bscTestnet } from "viem/chains";

const publicClient = createPublicClient({
  chain: bscTestnet,
  transport: http("https://data-seed-prebsc-1-s1.binance.org:8545"),
});

const walletClient = createWalletClient({
  chain: bscTestnet,
  transport: http("https://data-seed-prebsc-1-s1.binance.org:8545"),
  account: "0xYourWalletAddress",
});

const sdk = new HertzFlowSDK({
  chainId: 97,
  rpcUrl: "https://data-seed-prebsc-1-s1.binance.org:8545",
  oracleUrl: "https://oracle.hertzflow.com",
  statsUrl: "https://stats.hertzflow.com",
  publicClient,
  walletClient,
});
```

#### With WebSocket Support

```typescript
const sdk = new HertzFlowSDK({
  chainId: 97,
  rpcUrl: "https://data-seed-prebsc-1-s1.binance.org:8545",
  wsRpcUrl: "wss://bsc-testnet.publicnode.com",      // Enable real-time events
  oracleUrl: "https://oracle.hertzflow.com",
  statsUrl: "https://stats.hertzflow.com",
  account: "0xYourWalletAddress",
});
```

## API Reference

#### Read Methods

**Markets**

| Method                                   | Description                                             |
| ---------------------------------------- | ------------------------------------------------------- |
| `sdk.markets.getMarkets()`               | Fetch all available trading markets                     |
| `sdk.markets.getMarketsInfo()`           | Get comprehensive market data with prices and configs   |
| `sdk.markets.getMarketsConfigs(markets)` | Fetch market configuration parameters                   |
| `sdk.markets.getMarketsValues(params)`   | Get market runtime values (funding rates, pool amounts) |
| `sdk.markets.getDailyVolumes()`          | Get trading volumes per market                          |
| `sdk.markets.getTradingInstruments()`    | Get trading instruments with metadata                   |

**Positions**

| Method                                   | Description                                       |
| ---------------------------------------- | ------------------------------------------------- |
| `sdk.positions.getPositions(params)`     | Fetch raw position data for account               |
| `sdk.positions.getPositionsInfo(params)` | Get enhanced positions with calculated metrics    |
| `sdk.positions.getPositionsConstants()`  | Get system constants (min collateral, max orders) |
| `sdk.positions.getUserReferralInfo()`    | Get user's referral code and tier info            |

**Tokens**

| Method                                                | Description                              |
| ----------------------------------------------------- | ---------------------------------------- |
| `sdk.tokens.getTokensData()`                          | Fetch all available tokens with metadata |
| `sdk.tokens.getTokenRecentPrices()`                   | Get latest token prices from oracle      |
| `sdk.tokens.getTokensBalances(account?, tokensList?)` | Get user token balances                  |
| `sdk.tokens.getTokenTotalSupplies(tokenAddresses)`    | Get total supply of tokens               |

**Orders**

| Method                             | Description                              |
| ---------------------------------- | ---------------------------------------- |
| `sdk.orders.getOrders(params)`     | Fetch all user orders with filtering     |
| `sdk.orders.getOrdersInfo(params)` | Get enhanced order data with market info |

**Trades**

| Method                                   | Description                              |
| ---------------------------------------- | ---------------------------------------- |
| `sdk.trades.getTradeHistory(params)`     | Get market trade history                 |
| `sdk.trades.getUserTradeHistory(params)` | Get user's trade history with pagination |

**Claims**

| Method                                       | Description                          |
| -------------------------------------------- | ------------------------------------ |
| `sdk.claim.getClaimableFundingData(markets)` | Get claimable funding fees by market |
| `sdk.claim.getClaimableCollaterals(params)`  | Get claimable price impact rebates   |
| `sdk.claim.getClaimHistory(params)`          | Get claim history with pagination    |

**Utils**

| Method                                                        | Description                         |
| ------------------------------------------------------------- | ----------------------------------- |
| `sdk.utils.getGasLimits()`                                    | Fetch gas limits for all operations |
| `sdk.utils.getGasPrice()`                                     | Get current network gas price       |
| `sdk.utils.getEstimatedGasFee(type, params)`                  | Estimate gas for operation          |
| `sdk.utils.getExecutionFee(type, tokensData, prices, params)` | Calculate execution fee             |

## Write Methods

**Quick Methods**

| Method                     | Description                           |
| -------------------------- | ------------------------------------- |
| `sdk.orders.long(params)`  | Quick method to open a long position  |
| `sdk.orders.short(params)` | Quick method to open a short position |
| `sdk.orders.swap(params)`  | Quick method to execute a token swap  |

**Full Order Methods**

| Method                                      | Description                    |
| ------------------------------------------- | ------------------------------ |
| `sdk.orders.createIncreaseOrderTxn(params)` | Create position increase order |
| `sdk.orders.createDecreaseOrderTxn(params)` | Close or reduce position       |
| `sdk.orders.createSwapOrderTxn(params)`     | Execute token swap order       |
| `sdk.orders.updateOrderTxn(params)`         | Modify existing order          |
| `sdk.orders.cancelOrdersTxn(orderKeys)`     | Cancel one or multiple orders  |

**Pool Operations**

| Method                                      | Description             |
| ------------------------------------------- | ----------------------- |
| `sdk.orders.createHmDepositTxn(params)`     | Deposit to HM pool      |
| `sdk.orders.createHmWithdrawalTxn(params)`  | Withdraw from HM pool   |
| `sdk.orders.createHlvDepositTxn(params)`    | Deposit to HLV vault    |
| `sdk.orders.createHlvWithdrawalTxn(params)` | Withdraw from HLV vault |

**Token Operations**

| Method                                                                 | Description                  |
| ---------------------------------------------------------------------- | ---------------------------- |
| `sdk.orders.createWrapOrUnwrapTxn(params)`                             | Wrap or unwrap native tokens |
| `sdk.allowance.approveToken(tokenAddress, spenderAddress, amount?)`    | Approve token for spending   |
| `sdk.allowance.approveTokenForSyntheticsRouter(tokenAddress, amount?)` | Approve for SyntheticsRouter |

**Claim Operations**

| Method                                      | Description                     |
| ------------------------------------------- | ------------------------------- |
| `sdk.claim.claimFundingFees(params)`        | Claim funding fees for markets  |
| `sdk.claim.claimPriceImpactRebates(params)` | Claim price impact rebates      |
| `sdk.claim.claimAllRebates(params)`         | Batch claim funding and rebates |

## Event Subscriptions

**Position Events**

```typescript
sdk.events.subscribePositionIncrease((logs) => {
  console.log("Position increased:", logs);
});

sdk.events.subscribePositionDecrease((logs) => {
  console.log("Position decreased:", logs);
});
```

**Order Events**

```typescript
sdk.events.subscribeOrderCreated((logs) => {
  console.log("Order created:", logs);
});

sdk.events.subscribeOrderExecuted((logs) => {
  console.log("Order executed:", logs);
});

sdk.events.subscribeOrderCancelled((logs) => {
  console.log("Order cancelled:", logs);
});
```

**Deposit/Withdrawal Events**

```typescript
sdk.events.subscribeDepositCreated((logs) => { /* ... */ });
sdk.events.subscribeDepositExecuted((logs) => { /* ... */ });
sdk.events.subscribeWithdrawalCreated((logs) => { /* ... */ });
sdk.events.subscribeWithdrawalExecuted((logs) => { /* ... */ });
```

## Configuration Options

#### SDK Configuration Interface

```typescript
interface HertzFlowSdkConfig {
  chainId: ContractsChainId;              // Network ID (97 for BSC Testnet)
  account?: Address;                       // User's wallet address
  oracleUrl: string;                       // Oracle service URL
  rpcUrl: string;                          // RPC endpoint
  wsRpcUrl?: string;                       // WebSocket RPC (optional)
  statsUrl: string;                        // Statistics backend URL
  publicClient?: PublicClient;             // Custom viem public client
  walletClient?: WalletClient;             // Custom viem wallet client
  tokens?: Record<string, Partial<Token>>; // Token overrides
  markets?: Record<string, Partial<MarketSdkConfig>>; // Market overrides
  settings?: {
    uiFeeReceiverAccount?: string;         // UI fee receiver address
    ignoreTimeoutError?: boolean;          // Ignore timeout errors
  };
}
```

#### Supported Chains

| Chain       | Chain ID | Description             |
| ----------- | -------- | ----------------------- |
| BSC Testnet | 97       | BNB Smart Chain Testnet |

#### Token Customization

You can override token information:

```typescript
const sdk = new HertzFlowSDK({
  // ... other config
  tokens: {
    "0xTokenAddress": {
      name: "Custom Token Name",
      symbol: "CTN",
      imageUrl: "https://example.com/token.png",
    },
  },
});
```

#### Market Availability

Control which markets are available:

```typescript
const sdk = new HertzFlowSDK({
  // ... other config
  markets: {
    "0xMarketAddress": {
      isListed: false,  // Hide this market
    },
  },
});
```

#### UI Fee Configuration

Set up UI fee receiver:

```typescript
const sdk = new HertzFlowSDK({
  // ... other config
  settings: {
    uiFeeReceiverAccount: "0xYourFeeReceiverAddress",
  },
});
```

## Usage Examples

#### Opening a Long Position

```typescript
import { HertzFlowSDK } from "@hertzflow/sdk-v2";

const sdk = new HertzFlowSDK({
  chainId: 97,
  rpcUrl: "https://data-seed-prebsc-1-s1.binance.org:8545",
  oracleUrl: "https://oracle.hertzflow.com",
  statsUrl: "https://stats.hertzflow.com",
  account: "0xYourWalletAddress",
});

// Get market data and prices
const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();
const pricesData = await sdk.tokens.getTokenRecentPrices();

// Open a long position
const txn = await sdk.orders.long({
  payAmount: 1000000000n,                              // Amount in token decimals
  marketAddress: "0xMarketAddress",
  payTokenAddress: "0xPayTokenAddress",
  collateralTokenAddress: "0xCollateralTokenAddress",
  allowedSlippageBps: 125,                             // 1.25% slippage
  leverage: 50000n,                                    // 5x leverage (4 decimals)
  prices: pricesData,
});

console.log("Transaction:", txn);
```

#### Fetching Positions with Metrics

```typescript
// Get market info first
const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();
const pricesData = await sdk.tokens.getTokenRecentPrices();

// Get positions with full metrics
const positionsInfo = await sdk.positions.getPositionsInfo({
  marketsInfoData,
  tokensData,
  prices: pricesData,
  showPnlInLeverage: true,
});

// Access position data
for (const [key, position] of Object.entries(positionsInfo)) {
  console.log(`Position: ${position.marketInfo.name}`);
  console.log(`  Size: ${position.sizeInUsd}`);
  console.log(`  PnL: ${position.pnl}`);
  console.log(`  Leverage: ${position.leverage}`);
  console.log(`  Liquidation Price: ${position.liquidationPrice}`);
}
```

#### Subscribing to Real-Time Events

```typescript
// Enable WebSocket for real-time events
const sdk = new HertzFlowSDK({
  chainId: 97,
  rpcUrl: "https://data-seed-prebsc-1-s1.binance.org:8545",
  wsRpcUrl: "wss://bsc-testnet.publicnode.com",
  oracleUrl: "https://oracle.hertzflow.com",
  statsUrl: "https://stats.hertzflow.com",
  account: "0xYourWalletAddress",
});

// Subscribe to position events
const unsubscribeIncrease = sdk.events.subscribePositionIncrease((logs) => {
  logs.forEach((log) => {
    console.log("Position increased:", log);
  });
});

const unsubscribeDecrease = sdk.events.subscribePositionDecrease((logs) => {
  logs.forEach((log) => {
    console.log("Position decreased:", log);
  });
});

// Unsubscribe when done
// unsubscribeIncrease();
// unsubscribeDecrease();
```

#### Claiming Rewards

```typescript
// Get claimable data
const markets = await sdk.markets.getMarkets();
const claimableFunding = await sdk.claim.getClaimableFundingData(markets);

// Claim funding fees
if (Object.keys(claimableFunding.claimableFundingFees).length > 0) {
  const txn = await sdk.claim.claimFundingFees({
    marketAddresses: Object.keys(claimableFunding.claimableFundingFees),
    tokenAddresses: Object.values(claimableFunding.claimableFundingFees).flatMap(
      (m) => Object.keys(m)
    ),
  });
  console.log("Claim transaction:", txn);
}
```

## Account Management

#### Switching Accounts

```typescript
// Switch to a different account
sdk.setAccount("0xNewWalletAddress");

// This automatically:
// - Updates internal account reference
// - Triggers account-specific event listeners
// - Clears allowance subscriptions
```

#### Updating Wallet Client

```typescript
import { createWalletClient, http } from "viem";
import { bscTestnet } from "viem/chains";

const newWalletClient = createWalletClient({
  chain: bscTestnet,
  transport: http("https://data-seed-prebsc-1-s1.binance.org:8545"),
  account: "0xNewWalletAddress",
});

sdk.setWalletClient(newWalletClient);
```

### Resource Cleanup

Always destroy the SDK when done to clean up resources:

```typescript
// Clean up all resources
sdk.destroy();

// This:
// - Closes all WebSocket event listeners
// - Cleans up allowance event subscriptions
// - Releases internal references
```


---

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

```
GET https://hertzflow.gitbook.io/hertzflow-docs/tech-docs/hertzflow-sdk.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.
