Helius TypeScript SDK

repository·main·Indexed 42 days ago

https://github.com/helius-labs/helius-sdk

A TypeScript SDK for building on Solana, providing high-level access to Helius APIs and enhanced RPC functionality. Features include the DAS API for NFTs, ZK Compression support, Helius Sender for low-latency transaction submission, Webhooks, Laserstream, and the Enhanced Transactions API. Built on @solana/kit, version 3.2.0.

Tokens
25.8K
Snippets
67
Records
133
Agent score
52%

What's inside Helius SDK

  1. Subscribe to Pre-Confirmations for lowest latency

    main

    Pre-confirmations provide an early signal of scheduled transactions before they are shredded. This is an early signal, not a guarantee, and coverage depends on the share of stake forwarding to Helius.

    Use makePreconfWsClient or makePreconfWsClientForApiKey from helius-sdk/websockets/preconfWs.

    Subscription Details:

    • preconfSubscribe(): Streams all scheduled transactions. Returns an AsyncIterable of { version, slot, transactionIndex, status, transaction, transactionBytes }.
    • preconfUnsubscribe(subscriptionId): Unsubscribes from the stream.

    Data Format: Notifications are binary frames. The layout is: version:u8 | slot:u64_le | transaction_index:u64_le | status:u8 | bincode(VersionedTransaction).

    • status is a PreconfStatus enum: Failed = 0, Success = 1, Unknown = 2.

    Endpoint: Served from wss://beta.helius-rpc.com/?api-key=<KEY> (Production path).

    import { makePreconfWsClientForApiKey } from "helius-sdk/websockets/preconfWs";
    
    const client = makePreconfWsClientForApiKey(apiKey);
    const sub = await client.preconfSubscribe();
    for await (const event of sub) {
      // event.transaction is the decoded @solana/kit Transaction; event.transactionBytes is the raw bincode payload
      console.log(event.version, event.slot, event.transactionIndex, event.status);
    }
    await sub.unsubscribe();
    client.close();
  2. Configure a custom RPC transport for retries and failover

    main

    The createHelius function accepts a transport hook that follows the @solana/kit custom-transport pattern. This hook allows you to intercept and augment all JSON-RPC calls (standard Solana RPC and Helius-specific methods) made by the SDK.

    Note: This hook only covers JSON-RPC traffic. It does not affect WebSocket subscriptions (helius.ws) or REST sub-clients (e.g., webhooks, enhanced, wallet, admin, auth).

    To implement retries, wrap the defaultTransport. To implement failover, return a completely different transport implementation.

    import { createHelius, type RpcTransport } from "helius-sdk";
    
    const helius = createHelius({
      apiKey,
      transport: (defaultTransport: RpcTransport): RpcTransport => async (request) => {
        // Retry up to 3 times with exponential backoff
        let lastError: unknown;
        for (let attempt = 0; attempt < 3; attempt++) {
          try {
            return await defaultTransport(request);
          } catch (error) {
            lastError = error;
            await new Promise((r) => setTimeout(r, 2 ** attempt * 100));
          }
        }
        throw lastError;
      },
    });
  3. Use granular import paths for tree-shaking

    main

    The Helius SDK is ESM-first and supports granular imports to enable better tree-shaking. While the package is designed to be tree-shakable automatically by most bundlers (due to sideEffects: false), you can import specific modules directly via these subpaths:

    • RPC methods: helius-sdk/rpc/methods/<method>
    • Enhanced Transactions API: helius-sdk/enhanced/<method>
    • Staking: helius-sdk/staking/<method>
    • Transactions: helius-sdk/transactions/<method>
    • Types: helius-sdk/types/<type>
    • Webhooks: helius-sdk/webhooks/<method>
    • WebSockets: helius-sdk/websockets/<method>
    • ZK Compression: helius-sdk/zk/<method>
  4. Install the Helius TypeScript SDK

    main

    You can install the helius-sdk using your preferred package manager. pnpm is the recommended method.

    # Using pnpm (recommended)
    pnpm add helius-sdk
    
    # Using npm
    npm install helius-sdk
    
    # Using yarn
    yarn add helius-sdk
  5. Install the Helius SDK and Solana Kit

    main

    To use the Helius SDK, install the main package via npm. If you need to use Solana Kit primitives (like address() or lamports()) directly in your application code, you should also install @solana/kit.

    # Install the SDK
    npm i helius-sdk
    
    # Optional: install Kit if you need to use their helpers directly in your app
    npm i @solana/kit
  6. Use Version 1 transactions for larger sizes

    main

    To take advantage of the increased transaction size limit (up to 4,096 bytes) provided by Agave 4.2, you can opt into the Version 1 transaction format by passing version: 1 to createSmartTransaction.

    Key details for Version 1:

    • No Address Lookup Tables (ALTs): Version 1 does not support ALTs; all accounts must be listed inline. Use Version 0 if you require ALTs.
    • Automatic Compute Budget: The SDK handles compute-unit limits and priority fees in the transaction header. Do not pass ComputeBudgetProgram instructions manually, as they are no-ops in v1 and waste space.
    • Priority Fee Caps: You can cap the per-CU rate using priorityFeeCap or the absolute total spend using priorityFeeLamportsCap.
    • Constraints: V1 is capped at 64 instructions, 64 unique addresses, 12 signatures, and 255 accounts per instruction.
    const smart = await helius.tx.createSmartTransaction({
      signers: [feePayerSigner],
      instructions: [transferIx],
      version: 1,
      priorityFeeLamportsCap: 50_000, // Never spend more than 50k lamports on priority
    });
  7. Initialize the Helius client with createHelius()

    main

    In version 2.x and later, the SDK uses a factory function createHelius instead of the new Helius() constructor. This version is ESM-first, so use import instead of require. When initializing, pass an object containing your apiKey.

    import { createHelius } from "helius-sdk";
    import { address } from "@solana/kit";
    
    const helius = createHelius({ apiKey: process.env.HELIUS_API_KEY! });
    const assets = await helius.getAssetsByOwner({ ownerAddress: address("...") });
  8. Migrate from Helius SDK 1.x to 2.x

    main

    The SDK has been rewritten to use @solana/kit. Key changes include moving from a class constructor to a factory function, using Kit primitives for addresses and amounts, and updated namespaces for various APIs.

    Area1.x2.x
    Client initnew Helius()createHelius()
    Public keynew PublicKey(str)address(str)
    Amountsnew BN(...) / Number(...)lamports(...n)
    SignerKeypair.fromSecretKey(...)createKeyPairSignerFromBytes(...)
    Transactionshelius.rpc.<method>helius.tx.<method>
    DAS APIhelius.rpc.<method>helius.<method>
    Stakinghelius.rpc.<method>helius.stake.<method>
    Webhookshelius.<method>helius.webhooks.<method>
    Enhanced TxNo supporthelius.enhanced.<method>
    ZK CompressionNo supporthelius.zk.<method>
    WebSockets@solana/web3.js subscriptionshelius.ws.<method>
  9. Understand the Asset object in DAS API

    main

    The Asset interface represents a Solana digital asset returned by the Digital Asset Standard (DAS) API. It contains comprehensive data including:

    • Identity: id (mint address) and interface (token standard implementation).
    • Content: content (metadata, files, links) and inscription (on-chain inscription data).
    • Ownership: ownership (owner, delegation, frozen status) and authorities (scopes).
    • Metadata: mutable, burnt, creators, and royalty information.
    • Token Specifics: token_info (SPL metadata, price, balance), compression (for cNFTs), and mint_extensions (Token-2022 data).
    • Grouping: grouping (collections or other group memberships).
  10. Preconf WebSocket wire format

    main

    The Pre-confirmation stream uses a binary wire format (little-endian).

    Frame Layout: version:u8 (1) | slot:u64_le (8) | transaction_index:u64_le (8) | status:u8 (1) | bincode(VersionedTransaction)

    • Version Check: The first byte is the version. The client currently expects PRECONF_WIRE_VERSION (1). Frames with unknown versions are dropped.
    • Status Mapping: The status byte (at offset 17) maps to:
      • 0 $\rightarrow$ PreconfStatus.Failed
      • 1 $\rightarrow$ PreconfStatus.Success
      • Other $\rightarrow$ PreconfStatus.Unknown
  11. Get historical token balances at a specific point in time

    main

    Retrieve the balance of a specific token for a wallet at a historical point in time.

    Important Constraints:

    • You must provide exactly one of time (Unix timestamp in seconds), datetime (ISO 8601 string), or slot (Solana slot number).
    • For the most deterministic results, use slot.
    • For native SOL, use the pseudo-mint address: So11111111111111111111111111111111111111112.

    Response Note: The balance and balanceRaw fields are returned as strings to prevent precision loss for large values.

  12. Get token transfer activity

    main

    Retrieve a list of token transfers (inbound or outbound) for a specific wallet.

    Key Fields:

    • direction: Indicates if the transfer was in or out relative to the wallet.
    • counterparty: The address of the other party involved in the transfer.
    • amount: The human-readable transfer amount.
    • amountRaw: The raw amount in the smallest unit (e.g., lamports for SOL).

    Pagination: Use the cursor parameter with nextCursor from the response to fetch the next page.