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.
Installation
Section titled “Installation”Install the SDK and its peer dependencies using your preferred package manager:
npm install hyperstack-react zustandPeer Dependencies
Section titled “Peer Dependencies”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> );}Provider Props
Section titled “Provider Props”| Prop | Type | Default | Description |
|---|---|---|---|
network | 'mainnet' | 'devnet' | 'localnet' | NetworkConfig | undefined | The Solana network to connect to. |
websocketUrl | string | undefined | Overrides the network-default WebSocket URL. |
apiKey | string | undefined | Optional API key for authenticated access. |
autoConnect | boolean | true | Automatically connect to the WebSocket on mount. |
wallet | WalletAdapter | undefined | An optional wallet adapter for signing transactions. |
Stack Definition
Section titled “Stack Definition”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)}`, },});View Factories
Section titled “View Factories”createStateView<T>(viewPath, options?)
Section titled “createStateView<T>(viewPath, options?)”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 }
createListView<T>(viewPath, options?)
Section titled “createListView<T>(viewPath, options?)”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 }
Using Stacks
Section titled “Using Stacks”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> );}View Hook Parameters
Section titled “View Hook Parameters”The .use() method for views accepts:
- Params (
ListParamsorkeyobject) - Options (
ViewHookOptions)
ListParams
Section titled “ListParams”| Parameter | Type | Description |
|---|---|---|
key | string | Filter by partition key. |
where | Record<string, any> | Field-level filtering (supports eq, gt, gte, lt, lte). |
limit | number | Maximum number of records to return. |
filters | Record<string, string> | Custom server-side filters. |
ViewHookOptions
Section titled “ViewHookOptions”| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Set to false to pause subscription. |
initialData | any | undefined | Data to return before the first server response. |
refreshOnReconnect | boolean | false | Force a refresh when the WebSocket reconnects. |
View Hook Return Value (ViewHookResult)
Section titled “View Hook Return Value (ViewHookResult)”| Property | Type | Description |
|---|---|---|
data | T | T[] | undefined | The current state of the view data. |
isLoading | boolean | true until the first data frame is received. |
error | Error | undefined | Error object if the subscription fails. |
refresh | () => void | Manually trigger a refresh of the view. |
Transactions
Section titled “Transactions”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> );}useMutation Return Value
Section titled “useMutation Return Value”| Property | Type | Description |
|---|---|---|
submit | (instruction: any) => Promise<string> | Submits the transaction to the network. |
status | 'idle' | 'pending' | 'success' | 'error' | Current status of the mutation. |
signature | string | undefined | The transaction signature (available on success). |
error | string | undefined | Error message if the transaction fails. |
reset | () => void | Resets the mutation state to idle. |
Connection Management
Section titled “Connection Management”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> );}Connection States
Section titled “Connection States”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.
TypeScript Types
Section titled “TypeScript Types”The SDK exports several utility types to help you build typed components.
import type { StackDefinition, ViewDefinition, TransactionDefinition, ViewHookResult, ListParams} from 'hyperstack-react';Quick Reference
Section titled “Quick Reference”Exports
Section titled “Exports”| Export | Type | Description |
|---|---|---|
HyperstackProvider | Component | Context provider for the SDK. |
useHyperstack | Hook | Accesses stack views, transactions, and helpers. |
useConnectionState | Hook | Monitors WebSocket connection health. |
defineStack | Function | Creates a stack definition. |
createStateView | Function | View factory for single entities. |
createListView | Function | View factory for entity collections. |
HyperStreamError | Class | Custom error class for SDK errors. |