Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/hypertekorg/hyperstack/llms.txt

Use this file to discover all available pages before exploring further.

Overview

The HyperStack class is the main entry point for connecting to a HyperStack server and accessing real-time views, subscriptions, and instruction execution.

Installation

npm install @hyperstack/core

Quick Start

import { HyperStack } from '@hyperstack/core';

const stack = {
  name: 'my-stack',
  url: 'wss://api.example.com',
  views: {
    users: {
      state: { mode: 'state' as const, view: 'users.state' },
      list: { mode: 'list' as const, view: 'users.list' },
    },
  },
};

const client = await HyperStack.connect(stack);

Connection

HyperStack.connect()

Connect to a HyperStack server with the specified stack definition and options.
static async connect<T extends StackDefinition>(
  stack: T,
  options?: ConnectOptions
): Promise<HyperStack<T>>
stack
StackDefinition
required
Stack definition containing name, URL, views, and optional schemas/instructions
options
ConnectOptions
Optional connection configuration

ConnectOptions

url
string
WebSocket URL to connect to. Overrides stack.url if provided
storage
StorageAdapter
Custom storage adapter for persisting entity data. Defaults to MemoryAdapter
maxEntriesPerView
number | null
Maximum number of entities to keep per view. Set to null for unlimitedDefault: 10000
autoReconnect
boolean
Automatically reconnect on connection lossDefault: true
reconnectIntervals
number[]
Reconnection backoff intervals in millisecondsDefault: [1000, 2000, 4000, 8000, 16000]
maxReconnectAttempts
number
Maximum number of reconnection attemptsDefault: 5
flushIntervalMs
number
Interval for batching storage updates in milliseconds
validateFrames
boolean
Enable runtime validation of incoming frames using schemasDefault: false

Properties

views

Access typed views for querying and subscribing to entity data.
get views: TypedViews<TStack['views']>
const user = await client.views.users.state.get('user-123');
const allUsers = await client.views.users.list.get();
See Working with Views for detailed documentation.

instructions

Access instruction executors for invoking on-chain programs.
get instructions: InstructionsInterface<TStack['instructions']>
const result = await client.instructions.createUser(
  { name: 'Alice' },
  { wallet }
);
See Instruction Execution for detailed documentation.

connectionState

Get the current connection state.
get connectionState: ConnectionState
Possible values:
  • 'disconnected' - Not connected
  • 'connecting' - Connection in progress
  • 'connected' - Successfully connected
  • 'reconnecting' - Attempting to reconnect
  • 'error' - Connection error
const state = client.connectionState;
if (state === 'connected') {
  console.log('Ready to subscribe');
}

stackName

Get the name of the connected stack.
get stackName: string

store

Access the underlying storage adapter for direct data access.
get store: StorageAdapter

Methods

connect()

Manually initiate connection to the server.
async connect(): Promise<void>
const client = await HyperStack.connect(stack, { autoReconnect: false });
await client.connect(); // Manually connect

disconnect()

Disconnect from the server and clear all subscriptions.
disconnect(): void
client.disconnect();

isConnected()

Check if currently connected to the server.
isConnected(): boolean
if (client.isConnected()) {
  // Perform operations
}

clearStore()

Clear all cached entity data from storage.
clearStore(): void
client.clearStore();

onConnectionStateChange()

Listen for connection state changes.
onConnectionStateChange(
  callback: ConnectionStateCallback
): UnsubscribeFn
callback
(state: ConnectionState, error?: string) => void
required
Function called when connection state changes
Returns: Unsubscribe function
const unsubscribe = client.onConnectionStateChange((state, error) => {
  console.log('Connection state:', state);
  if (error) {
    console.error('Connection error:', error);
  }
});

// Stop listening
unsubscribe();

onFrame()

Listen for raw frames received from the server.
onFrame(callback: (frame: Frame) => void): UnsubscribeFn
const unsubscribe = client.onFrame((frame) => {
  console.log('Received frame:', frame);
});

Advanced Usage

Custom Storage Adapter

Use a custom storage adapter for persistence or state management integration.
import { HyperStack } from '@hyperstack/core';
import { IndexedDBAdapter } from '@hyperstack/storage-indexeddb';

const storage = new IndexedDBAdapter({ dbName: 'my-app' });

const client = await HyperStack.connect(stack, {
  storage,
});
See Storage Adapters for implementation details.

Schema Validation

Enable runtime validation of incoming data using Zod or similar schemas.
import { z } from 'zod';

const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
});

const stack = {
  name: 'my-stack',
  url: 'wss://api.example.com',
  views: { /* ... */ },
  schemas: {
    'users.state': UserSchema,
  },
};

const client = await HyperStack.connect(stack, {
  validateFrames: true,
});

Bounded Memory Usage

Limit the number of entities stored per view to prevent unbounded memory growth.
const client = await HyperStack.connect(stack, {
  maxEntriesPerView: 1000, // Keep max 1000 entities per view
});
When the limit is reached, the oldest entities are evicted using LRU (Least Recently Used) strategy.

Type Exports

import type {
  HyperStackOptions,
  HyperStackOptionsWithStorage,
  ConnectOptions,
  StackDefinition,
  ConnectionState,
  ConnectionStateCallback,
  UnsubscribeFn,
} from '@hyperstack/core';

Error Handling

import { HyperStackError } from '@hyperstack/core';

try {
  const client = await HyperStack.connect(stack);
} catch (error) {
  if (error instanceof HyperStackError) {
    console.error(`${error.code}: ${error.message}`);
    console.error('Details:', error.details);
  }
}

Next Steps

Working with Views

Learn how to query and subscribe to real-time data

Subscriptions

Manage real-time subscriptions and updates

Storage Adapters

Integrate with state management libraries

Instructions

Execute on-chain program instructions

Build docs developers (and LLMs) love