Skip to content

TypeScript SDK

The Hyperstack TypeScript SDK (hyperstack-react) provides a high-level React integration for building real-time Solana applications. It features a type-safe API for data streaming, transaction management, and state synchronization.

Install the SDK and its peer dependencies using your preferred package manager:

Terminal window
npm install hyperstack-react zustand

The SDK requires the following peer dependencies:

  • React (v19.0.0+)
  • Zustand (v4.0.0+) - Used for internal state management

Wrap your application with the HyperstackProvider to initialize the runtime and provide connection context to your components.

import { HyperstackProvider } from 'hyperstack-react';
function App() {
return (
<HyperstackProvider
network="devnet"
autoConnect={true}
>
<Dashboard />
</HyperstackProvider>
);
}
PropTypeDefaultDescription
network'mainnet' | 'devnet' | 'localnet' | NetworkConfigundefinedThe Solana network to connect to.
websocketUrlstringundefinedOverrides the network-default WebSocket URL.
apiKeystringundefinedOptional API key for authenticated access.
autoConnectbooleantrueAutomatically connect to the WebSocket on mount.
walletWalletAdapterundefinedAn optional wallet adapter for signing transactions.

A Stack defines the data structure and operations of your application. Use defineStack to create a typed definition that the SDK uses to generate hooks and helper methods.

import { defineStack, createStateView, createListView } from 'hyperstack-react';
export const TokenStack = defineStack({
name: 'token-tracker',
// Real-time data views
views: {
tokens: {
list: createListView<Token>('Token/list'),
state: createStateView<Token>('Token/state'),
},
},
// Transaction builders
transactions: {
transfer: {
build: (params: { to: string; amount: number }) => ({
instruction: 'transfer',
params,
}),
refresh: [{ view: 'tokens/list' }],
},
},
// Utility helpers
helpers: {
formatPrice: (price: number) => `$${price.toFixed(2)}`,
},
});

Creates a view definition for a single entity state.

  • viewPath: The server-side path for the view (e.g., 'Entity/state').
  • options: { transform?: (data: any) => T }

Creates a view definition for a collection of entities.

  • viewPath: The server-side path for the view (e.g., 'Entity/list').
  • options: { transform?: (data: any) => T }

The useHyperstack hook provides access to the typed interface of your stack.

import { useHyperstack } from 'hyperstack-react';
import { TokenStack } from './stacks';
function TokenList() {
const stack = useHyperstack(TokenStack);
// Using a list view
const { data: tokens, isLoading } = stack.views.tokens.list.use({
limit: 10,
where: { volume: { gte: 1000 } }
});
// Using a state view
const { data: globalStats } = stack.views.tokens.state.use({
key: 'global'
});
if (isLoading) return <p>Loading...</p>;
return (
<div>
{tokens?.map(t => (
<div key={t.id}>{stack.helpers.formatPrice(t.price)}</div>
))}
</div>
);
}

The .use() method for views accepts:

  1. Params (ListParams or key object)
  2. Options (ViewHookOptions)
ParameterTypeDescription
keystringFilter by partition key.
whereRecord<string, any>Field-level filtering (supports eq, gt, gte, lt, lte).
limitnumberMaximum number of records to return.
filtersRecord<string, string>Custom server-side filters.
OptionTypeDefaultDescription
enabledbooleantrueSet to false to pause subscription.
initialDataanyundefinedData to return before the first server response.
refreshOnReconnectbooleanfalseForce a refresh when the WebSocket reconnects.
PropertyTypeDescription
dataT | T[] | undefinedThe current state of the view data.
isLoadingbooleantrue until the first data frame is received.
errorError | undefinedError object if the subscription fails.
refresh() => voidManually trigger a refresh of the view.

Handle mutations and transaction lifecycle using the useMutation hook provided by the stack client.

function TransferButton() {
const stack = useHyperstack(TokenStack);
const { submit, status, signature, error } = stack.tx.useMutation();
const handleTransfer = async () => {
const tx = stack.tx.transfer({ to: '...', amount: 100 });
await submit(tx);
};
return (
<button onClick={handleTransfer} disabled={status === 'pending'}>
{status === 'pending' ? 'Sending...' : 'Transfer'}
</button>
);
}
PropertyTypeDescription
submit(instruction: any) => Promise<string>Submits the transaction to the network.
status'idle' | 'pending' | 'success' | 'error'Current status of the mutation.
signaturestring | undefinedThe transaction signature (available on success).
errorstring | undefinedError message if the transaction fails.
reset() => voidResets the mutation state to idle.

Monitor the health of the WebSocket connection using the useConnectionState hook.

import { useConnectionState } from 'hyperstack-react';
function ConnectionStatus() {
const state = useConnectionState();
return (
<div className={`status-${state}`}>
Connection: {state}
</div>
);
}
  • disconnected: Initial state, not connected.
  • connecting: Attempting to establish a connection.
  • connected: Active and healthy connection.
  • reconnecting: Automatically trying to reconnect after a failure.
  • error: Connection failed or reached max retry attempts.

The SDK exports several utility types to help you build typed components.

import type {
StackDefinition,
ViewDefinition,
TransactionDefinition,
ViewHookResult,
ListParams
} from 'hyperstack-react';

ExportTypeDescription
HyperstackProviderComponentContext provider for the SDK.
useHyperstackHookAccesses stack views, transactions, and helpers.
useConnectionStateHookMonitors WebSocket connection health.
defineStackFunctionCreates a stack definition.
createStateViewFunctionView factory for single entities.
createListViewFunctionView factory for entity collections.
HyperStreamErrorClassCustom error class for SDK errors.