Constructors

Properties

api: O2Api

The underlying low-level REST API client.

Accessors

Methods

  • Enables await using client = new O2Client(...).

    Returns Promise<void>

  • Submit a batch of type-safe actions grouped by market.

    This is the primary batch interface. Actions use the Action union with dual-mode Numeric values — string decimals are auto-scaled, bigint values pass through directly.

    Market resolution, price/quantity scaling, FractionalPrice adjustment, min_order validation, and accounts registry lookup are all handled internally.

    Parameters

    • marketActions: MarketActionGroup[]

      Groups of actions per market.

    • collectOrders: boolean = false

      Whether to return order details in response (default: false).

    Returns Promise<SessionActionsResponse>

    await client.batchActions([
    { market: "fFUEL/fUSDC", actions: [
    settleBalanceAction(),
    createOrderAction("buy", "0.02", "100"),
    createOrderAction("sell", "0.05", "50", "PostOnly"),
    ]}
    ], true);
  • Close all connections and release resources.

    Returns void

  • Create an order with automatic encoding, signing, and nonce management.

    Price and quantity accept dual-mode Numeric values:

    • string — human-readable decimal (e.g., "0.02", "100") — auto-scaled
    • bigint — raw chain integer (e.g., 20000000n) — pass-through

    Parameters

    • market: MarketRef

      Market pair string or Market object.

    • side: "buy" | "sell"

      Order side ("buy" or "sell").

    • price: Numeric

      Order price as decimal string or raw bigint.

    • quantity: Numeric

      Order quantity as decimal string or raw bigint.

    • Optionaloptions: CreateOrderOptions

      Optional order parameters.

    Returns Promise<SessionActionsResponse>

  • Create a trading session.

    The trade account ID is resolved automatically from the wallet address.

    Parameters

    • wallet: Signer

      The owner wallet.

    • markets: MarketRef[]

      Market pairs or Market objects to authorize.

    • expiryDays: number = 30

      Session expiry in days (default: 30).

    Returns Promise<SessionState>

  • Disconnect WebSocket if connected.

    Returns void

  • Fetch OHLCV candlestick bars.

    Parameters

    • market: MarketRef

      Market pair string or Market object.

    • resolution: string

      Bar resolution (e.g., "1m", "1h", "1d").

    • from: number

      Start time in milliseconds (not seconds).

    • to: number

      End time in milliseconds (not seconds).

    Returns Promise<Bar[]>

  • Fetch the order book depth snapshot.

    Parameters

    • market: MarketRef

      Market pair string or Market object.

    • precision: number = 1

      Price grouping level, from 1 (most precise) to 18 (most grouped). Default 1. At level 1, prices are at or near their exact values. Higher levels round prices into larger buckets — useful for a visual depth chart but too coarse for trading. Same scale as streamDepth.

    • Optionallimit: number

      Maximum number of price levels per side (bids/asks). undefined (default) returns the full order book.

    Returns Promise<DepthSnapshot>

    If precision is outside the valid range 1--18.

  • Resolve a market by symbol pair (e.g., "fFUEL/fUSDC") or hex market ID.

    Parameters

    • symbolPair: string

      The market pair or hex ID.

    Returns Promise<Market>

    O2Error if the market is not found.

  • Fetch all available markets. Results are cached with stale-while-revalidate.

    Returns Promise<Market[]>

  • Fetch the current on-chain nonce for a trading account.

    Parameters

    Returns Promise<bigint>

  • Fetch orders for an account on a market.

    Parameters

    • market: MarketRef

      Market pair string or Market object.

    • tradeAccountId: TradeAccountId

      The trade account contract ID.

    • OptionalisOpen: boolean

      Filter by open/closed status.

    • count: number = 20

      Number of orders (default: 20, max 200).

    • Optionalcursor: { startOrderId: string; startTimestamp: number }

      Optional pagination cursor. Pass the timestamp and order_id from the last order of the previous page.

    Returns Promise<Order[]>

  • Fetch recent trades for a market.

    Parameters

    • market: MarketRef

      Market pair string or Market object.

    • count: number = 50

      Number of trades to return (default: 50, max 50).

    • Optionalaccount: string | TradeAccountId

      Optional trade account ID to filter trades for a specific account.

    • Optionalcursor: { startTimestamp: number; startTradeId: string }

      Optional pagination cursor. Pass the timestamp and trade_id from the last trade of the previous page.

    Returns Promise<Trade[]>

  • Re-fetch the nonce from the API and update the stored session state.

    Returns Promise<bigint>

    The fresh nonce value.

    Call this after errors to re-sync the nonce (it increments on-chain even on reverts).

  • Idempotent account setup. Safe to call on every bot startup.

    1. Check if account exists
    2. Create if needed
    3. Mint via faucet (testnet/devnet) - non-fatal on cooldown
    4. Whitelist account
    5. Return trade_account_id and nonce

    Parameters

    Returns Promise<{ nonce: bigint; tradeAccountId: TradeAccountId }>

  • Stream real-time order book depth updates.

    Parameters

    • market: MarketRef

      Market pair string or Market object.

    • precision: number = 1

      Price grouping level, from 1 (most precise) to 18 (most grouped). Default 1. At level 1, prices are at or near their exact values. Higher levels round prices into larger buckets. Same scale as getDepth.

    Returns Promise<AsyncGenerator<DepthUpdate, any, any>>

    An async generator yielding DepthUpdate messages.

    If precision is outside the valid range 1--18.

  • Stream WebSocket connection lifecycle events.

    Yields ConnectionEvent objects whenever the connection state changes (connected, disconnected, reconnecting, reconnected, closed).

    Use this to detect reconnects and re-sync critical state from the REST API — messages during the disconnect window are lost.

    Returns Promise<AsyncGenerator<ConnectionEvent, any, any>>

    for await (const event of client.streamLifecycle()) {
    if (event.state === "reconnected") {
    const balances = await client.getBalances(account);
    } else if (event.state === "closed") {
    break;
    }
    }
  • Mint test assets from faucet directly to the owner's trading account contract.

    This is useful for explicit testnet/devnet top-ups after account setup.

    Parameters

    • wallet: Signer

      The owner wallet.

    Returns Promise<FaucetResponse>

    Faucet mint response.

    O2Error if no trade account exists or faucet is unavailable.

  • Withdraw funds from trading account to owner wallet.

    Parameters

    • wallet: Signer

      The owner wallet (not session key).

    • asset: string

      Asset symbol (e.g., "fUSDC") or hex asset ID.

    • amount: Numeric

      Amount as human-readable string or raw bigint.

    • Optionalto: string

      Destination address (defaults to wallet address).

    Returns Promise<WithdrawResponse>

  • Generate a new Fuel-native secp256k1 wallet.

    Returns WalletState

    A new wallet state with a random private key.

    const wallet = O2Client.generateWallet();
    console.log(wallet.b256Address); // "0x..."
  • Load an EVM-compatible wallet from a private key hex string.

    Parameters

    • privateKeyHex: string

      The private key as a 0x-prefixed hex string.

    Returns WalletState

    The loaded wallet state with EVM address.

  • Load a Fuel-native wallet from a private key hex string.

    Parameters

    • privateKeyHex: string

      The private key as a 0x-prefixed hex string.

    Returns WalletState

    The loaded wallet state.