跳转到主要内容
Helius TypeScript SDK为所有Helius API提供类型安全的方法,使代理与Solana进行交互的速度最快。
  • Package: helius-sdk (npm / pnpm / yarn)
  • Version: 2.x (使用 @solana/kit,而不是 @solana/web3.js)
  • Runtime: 任何JavaScript运行时 — 浏览器、Deno、Bun、edge runtimes(Cloudflare Workers, Vercel Edge), Node.js 20+
  • TypeScript: 5.8+ (包含完整类型定义)
  • License: ISC

安装

npm install helius-sdk

快速开始

import { createHelius } from "helius-sdk";

const helius = createHelius({
  apiKey: "YOUR_API_KEY",
  network: "mainnet", // or "devnet"
});

// Get all NFTs and tokens owned by a wallet
const assets = await helius.getAssetsByOwner({
  ownerAddress: "86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY",
  page: 1,
  limit: 50,
});

// Get transaction history (with token account activity)
const txs = await helius.getTransactionsForAddress([
  "86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY",
  { limit: 100, transactionDetails: "full", filters: { tokenAccounts: "balanceChanged" } },
]);

// Send a transaction via Helius Sender (ultra-low latency)
const sig = await helius.tx.sendTransactionWithSender({
  instructions: [transferInstruction],
  signers: [walletSigner],
  region: "US_EAST",
});

客户端选项

const helius = createHelius({
  apiKey: "YOUR_API_KEY",       // Required for webhooks, enhanced txs, wallet API
  network: "mainnet",           // "mainnet" (default) or "devnet"
  baseUrl: "https://custom..",  // Override RPC URL (optional)
  rebateAddress: "wallet",      // Wallet for RPC rebates (optional)
  userAgent: "my-agent/1.0",   // Sent as X-Helius-Client header (optional)
});

命名空间

所有方法通过helius客户端访问。DAS API 方法和标准Solana RPC 方法可直接在helius.*上使用。其他功能组织为命名空间:
Namespace访问目的
DAS APIhelius.getAsset(), helius.getAssetsByOwner(), 等查询NFTs、代币、压缩资产
RPC V2helius.getTransactionsForAddress(), helius.getProgramAccountsV2()增强的RPC,支持分页和过滤
Transactionshelius.tx.*智能交易和Helius Sender
Enhancedhelius.enhanced.*将交易解析成人类可读格式
Webhookshelius.webhooks.*创建和管理webhook订阅
WebSocketshelius.ws.*实时区块链数据流
Stakinghelius.stake.*将SOL质押到Helius验证者
ZK Compressionhelius.zk.*压缩账户和证明
Wallet APIhelius.wallet.*余额、历史、身份查找
Standard RPChelius.getBalance(), helius.getSlot(), 等通过代理实现所有标准Solana RPC方法
Raw RPChelius.raw直接访问底层@solana/kit Rpc客户端
Authimport { makeAuthClient } from "helius-sdk/auth/client"代理注册和API密钥管理(独立导入)

对代理的建议

使用 getTransactionsForAddress 代替两步查找

getTransactionsForAddress 将签名查找和交易获取合并为一个调用,并进行服务器端过滤。它支持时间/插槽范围、令牌账户过滤和分页。
// GOOD: Single call, server-side filtering
const txs = await helius.getTransactionsForAddress([
  "address",
  {
    transactionDetails: "full",
    limit: 100,
    filters: {
      tokenAccounts: "balanceChanged",
      blockTime: { gte: Math.floor(Date.now() / 1000) - 86400 },
    },
  },
]);

// BAD: Two calls, client-side filtering, no token account support
const sigs = await helius.raw.getSignaturesForAddress(address).send();
const txs = await Promise.all(sigs.map(s => helius.raw.getTransaction(s.signature).send()));

使用 sendSmartTransaction 进行标准发送

它自动模拟、估算计算单元、获取优先费用并确认。不要手动构建 ComputeBudget 指令——SDK 会自动添加它们。
const sig = await helius.tx.sendSmartTransaction({
  instructions: [yourInstruction],
  signers: [walletSigner],
  commitment: "confirmed",
  priorityFeeCap: 100_000,   // Optional: cap fees in microlamports/CU
  bufferPct: 0.1,            // 10% compute unit headroom (default)
});

使用 Helius Sender 实现超低延迟

对于时间敏感的交易(套利、抢购、清算),使用 sendTransactionWithSender。它通过 Helius 的多区域基础设施和 Jito 路由。
const sig = await helius.tx.sendTransactionWithSender({
  instructions: [yourInstruction],
  signers: [walletSigner],
  region: "US_EAST",          // Default, US_SLC, US_EAST, EU_WEST, EU_CENTRAL, EU_NORTH, AP_SINGAPORE, AP_TOKYO
  swqosOnly: true,            // Route through SWQOS only (lower tip requirement)
  pollTimeoutMs: 60_000,
  pollIntervalMs: 2_000,
});

在处理多个资产时使用 getAssetBatch

当获取多个资产时,将它们批量处理。不要在循环中调用 getAsset
// GOOD: Single request
const assets = await helius.getAssetBatch({
  ids: ["mint1", "mint2", "mint3"],
  options: { showFungible: true, showCollectionMetadata: true },
});

// BAD: N requests
const assets = await Promise.all(mints.map(id => helius.getAsset({ id })));

使用 webhooks 或 WebSockets 代替轮询

不要在循环中轮询 getTransactionsForAddress。使用 webhooks 进行服务器到服务器的通知或 WebSockets 进行实时客户端流传输。
// Webhook: server receives POST on matching transactions
const webhook = await helius.webhooks.create({
  webhookURL: "https://your-server.com/webhook",
  webhookType: "enhanced",
  transactionTypes: ["TRANSFER", "NFT_SALE", "SWAP"],
  accountAddresses: ["address_to_monitor"],
  authHeader: "Bearer your-secret",
});

// WebSocket: stream logs in real-time
const req = await helius.ws.logsNotifications({ mentions: ["address"] });
const stream = await req.subscribe({ abortSignal: controller.signal });
for await (const log of stream) {
  console.log(log);
}

分页

SDK 根据方法使用不同的分页策略。

基于令牌/游标(RPC V2 方法)

// getTransactionsForAddress uses paginationToken
let paginationToken = null;
const allTxs = [];
do {
  const result = await helius.getTransactionsForAddress([
    "address",
    { limit: 100, paginationToken },
  ]);
  allTxs.push(...result.data);
  paginationToken = result.paginationToken;
} while (paginationToken);

// getProgramAccountsV2 uses paginationKey
let paginationKey = null;
do {
  const result = await helius.getProgramAccountsV2([
    programId,
    { limit: 1000, paginationKey },
  ]);
  // process result.accounts
  paginationKey = result.paginationKey;
} while (paginationKey);

基于页面(DAS API)

let page = 1;
const allAssets = [];
while (true) {
  const result = await helius.getAssetsByOwner({ ownerAddress: "...", page, limit: 1000 });
  allAssets.push(...result.items);
  if (result.items.length < 1000) break;
  page++;
}

tokenAccounts 过滤器

查询 getTransactionsForAddress 时,tokenAccounts 过滤器控制是否包括令牌账户活动:
行为适用场合
省略 / "none"仅涉及地址的交易仅关心 SOL 转账和程序调用
"balanceChanged"还包括改变余额的令牌交易推荐用于大多数代理 — 显示令牌发送/接收而无杂音
"all"包括所有令牌账户交易需要完整的令牌活动(可能返回很多结果)

changedSinceSlot — 增量账号获取

changedSinceSlot 仅返回在给定 slot 之后修改的账户。对同步或索引工作流有用。由 getProgramAccountsV2, getTokenAccountsByOwnerV2, getAccountInfo, getMultipleAccounts, getProgramAccountsgetTokenAccountsByOwner 支持。
// First fetch: get all accounts
const baseline = await helius.getProgramAccountsV2([programId, { limit: 10_000 }]);
const lastSlot = currentSlot;

// Later: only get accounts that changed since your last fetch
const updates = await helius.getProgramAccountsV2([
  programId,
  { limit: 10_000, changedSinceSlot: lastSlot },
]);

常见错误

  1. transactionDetails: "full" 不是默认值 — 默认情况下,getTransactionsForAddress 仅返回签名。设置 transactionDetails: "full" 以获取完整的交易数据。
  2. 不要使用 sendSmartTransaction 添加 ComputeBudget 指令 — SDK 会自动添加它们。自行添加会导致指令重复和交易失败。
  3. 优先费用以微 lamports 每计算单位计算 — 不是 lamports。来自 getPriorityFeeEstimate 的值已经是适用于 SetComputeUnitPrice 的正确单位。
  4. DAS 分页从 1 开始page: 1 是第一页,而不是 page: 0
  5. blockTime 是 Unix 秒,而不是毫秒 — 过滤时使用 Math.floor(Date.now() / 1000)
  6. getAsset 默认隐藏可替代代币 — 传递 options: { showFungible: true } 以包含它们。
  7. WebSocket 流需要清理 — 完成后始终使用 AbortController 信号并调用 helius.ws.close() 以避免连接泄漏。

错误处理和重试

SDK 抛出带有嵌入消息字符串中 HTTP 状态代码的原生 Error 对象(例如,"API error (429): ...")。错误对象没有 .status 属性,因此状态检测需要解析消息。
async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      const msg = error instanceof Error ? error.message : "";
      const status = msg.match(/\b(\d{3})\b/)?.[1];
      const retryable = status === "429" || (status && status.startsWith("5"));
      if (!retryable || attempt === maxRetries) throw error;
      await new Promise(r => setTimeout(r, 1000 * 2 ** attempt));
    }
  }
  throw new Error("Unreachable");
}
状态含义操作
401API 密钥无效或缺失检查 API 密钥
429超出速率限制或信用额度后退并重试
5xx服务器错误使用指数退避重试

编程注册(认证模块)

auth 模块是一个独立的导入,它不在主 HeliusClient 上。可用于编程代理注册流程。
import { makeAuthClient } from "helius-sdk/auth/client";

const auth = makeAuthClient();

// All-in-one shortcut:
const result = await auth.agenticSignup({ secretKey: keypair.secretKey });
// result: { jwt, walletAddress, projectId, apiKey, endpoints, credits }

// Or step-by-step:
const keypair = await auth.generateKeypair();
const address = await auth.getAddress(keypair);
const { message, signature } = await auth.signAuthMessage(keypair.secretKey);
const { token } = await auth.walletSignup(message, signature, address);
const project = await auth.createProject(token);
const apiKey = await auth.createApiKey(token, project.id, address);

API 快速参考

以下是 Helius TypeScript SDK 支持的所有 API 方法的完整列表:

DAS API(数字资产标准)

helius.getAsset({ id })                                    // Single asset by mint
helius.getAssetBatch({ ids })                              // Multiple assets
helius.getAssetsByOwner({ ownerAddress, page, limit })     // Assets by wallet
helius.getAssetsByAuthority({ authorityAddress })           // Assets by update authority
helius.getAssetsByCreator({ creatorAddress })               // Assets by creator
helius.getAssetsByGroup({ groupKey, groupValue })           // Assets by collection
helius.searchAssets({ ownerAddress, tokenType, ... })       // Flexible search
helius.getAssetProof({ id })                               // Merkle proof (cNFTs)
helius.getAssetProofBatch({ ids })                         // Batch Merkle proofs
helius.getTokenAccounts({ owner })                         // Token accounts
helius.getNftEditions({ id })                              // Print editions
helius.getSignaturesForAsset({ id })                       // Transaction history for asset

RPC V2 方法

helius.getTransactionsForAddress([address, config])        // Transaction history (paginationToken)
helius.getProgramAccountsV2([programId, config])           // Program accounts (paginationKey)
helius.getTokenAccountsByOwnerV2([owner, filter?, config]) // Token accounts (paginationKey)
helius.getPriorityFeeEstimate({ accountKeys, options })    // Fee estimates

交易

helius.tx.sendSmartTransaction({ instructions, signers })  // Auto-optimized send
helius.tx.createSmartTransaction({ instructions, signers })// Build without sending
helius.tx.sendTransactionWithSender({ ..., region })       // Helius Sender (low latency)

增强交易

helius.enhanced.getTransactions({ transactions })          // Parse by signatures
helius.enhanced.getTransactionsByAddress({ address })      // Parse by address

Webhooks

helius.webhooks.create({ webhookURL, transactionTypes, accountAddresses })
helius.webhooks.get(webhookID)
helius.webhooks.getAll()
helius.webhooks.update(webhookID, params)
helius.webhooks.delete(webhookID)

WebSockets

helius.ws.logsNotifications(filter, config)                // Transaction logs
helius.ws.accountNotifications(address, config)            // Account changes
helius.ws.signatureNotifications(signature, config)        // Tx confirmation
helius.ws.slotNotifications(config)                        // Slot updates
helius.ws.programNotifications(programId, config)          // Program account changes
helius.ws.close()                                          // Clean up connections

质押

helius.stake.createStakeTransaction(owner, amountSol)                          // Stake SOL
helius.stake.createUnstakeTransaction(ownerSigner, stakeAccount)               // Unstake
helius.stake.createWithdrawTransaction(withdrawAuth, stakeAcct, dest, lamports)// Withdraw
helius.stake.getHeliusStakeAccounts(wallet)                // List stake accounts

钱包 API

helius.wallet.getBalances({ wallet })                      // Token balances
helius.wallet.getHistory({ wallet })                       // Transaction history
helius.wallet.getTransfers({ wallet })                     // Transfer history
helius.wallet.getIdentity({ wallet })                      // Known identity lookup
helius.wallet.getBatchIdentity({ addresses })              // Batch identity (max 100)
helius.wallet.getFundedBy({ wallet })                      // Funding source

ZK 压缩

helius.zk.getCompressedAccount({ address })                // Single compressed account
helius.zk.getCompressedAccountsByOwner({ owner })          // By owner
helius.zk.getCompressedTokenAccountsByOwner({ owner })     // Compressed tokens
helius.zk.getCompressedAccountProof({ hash })              // Merkle proof
helius.zk.getCompressedBalance({ address })                // Balance
helius.zk.getValidityProof({ hashes })                     // Validity proof

标准 Solana RPC

所有标准 Solana RPC 方法都可以直接在 helius.* 上使用,并通过底层 @solana/kit Rpc 客户端代理:
const balance = await helius.getBalance(address).send();
const blockhash = await helius.getLatestBlockhash().send();
const slot = await helius.getSlot().send();
这个 helius.raw 属性以相同的方式显式公开客户端,对于需要标准 Rpc 对象的第三方库非常有用。

资源