跳转到主要内容
Helius Rust SDK为所有Helius API提供异步Rust绑定,非常适合高性能代理工作负载。
  • Crate: helius (crates.io)
  • Version: 1.x (使用 solana-client 3.0, solana-sdk 3.0)
  • Runtime: 异步 (tokio 1.x)
  • Rust: 1.85+ (edition 2021)
  • HTTP Client: reqwest
  • License: MIT

安装

[dependencies]
helius = "1.0.0"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
solana-sdk = "3.0.0"
crate默认使用native-tls。对于纯Rust TLS(在OpenSSL不可用时有用),使用:
helius = { version = "1.0.0", default-features = false, features = ["rustls"] }

快速入门

use helius::error::Result;
use helius::types::*;
use helius::Helius;

#[tokio::main]
async fn main() -> Result<()> {
    let helius = Helius::new("YOUR_API_KEY", Cluster::MainnetBeta)?;

    // Get all NFTs owned by a wallet
    let assets = helius.rpc().get_assets_by_owner(GetAssetsByOwner {
        owner_address: "86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY".to_string(),
        page: 1,
        limit: Some(50),
        ..Default::default()
    }).await?;

    // Get transaction history (with token account activity)
    let txs = helius.rpc().get_transactions_for_address(
        "86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY".to_string(),
        GetTransactionsForAddressOptions {
            limit: Some(100),
            transaction_details: Some(TransactionDetails::Full),
            filters: Some(GetTransactionsFilters {
                token_accounts: Some(TokenAccountsFilter::BalanceChanged),
                ..Default::default()
            }),
            ..Default::default()
        },
    ).await?;

    // Send a transaction via Helius Sender (ultra-low latency)
    let sig = helius.send_smart_transaction_with_sender(
        SmartTransactionConfig {
            create_config: CreateSmartTransactionConfig {
                instructions: vec![transfer_instruction],
                signers: vec![wallet_signer],
                ..Default::default()
            },
            ..Default::default()
        },
        SenderSendOptions {
            region: "US_EAST".to_string(),
            ..Default::default()
        },
    ).await?;

    Ok(())
}

客户端构造器

Helius::new — 基本同步客户端

let helius = Helius::new("YOUR_API_KEY", Cluster::MainnetBeta)?;
最简单的构造器。不需要.await。提供RPC方法、webhook、增强型交易、智能交易和钱包API。不支持异步Solana客户端或WebSocket。

Helius::new_async — 功能齐全的异步客户端

let helius = Helius::new_async("YOUR_API_KEY", Cluster::MainnetBeta).await?;
推荐用于生产环境。包括异步Solana RPC客户端和增强型WebSocket流。需要.await,因为它建立了WebSocket连接。

Helius::new_with_url — 自定义RPC端点

let helius = Helius::new_with_url("http://localhost:8899")?;
适用于专用RPC节点、代理或本地开发。不需要API密钥。

HeliusBuilder — 高级配置

use helius::HeliusBuilder;

let helius = HeliusBuilder::new()
    .with_api_key("YOUR_API_KEY")?
    .with_cluster(Cluster::MainnetBeta)
    .with_async_solana()
    .with_websocket(None, None)
    .with_commitment(CommitmentConfig::confirmed())
    .build()
    .await?;

HeliusFactory — 多集群

let factory = HeliusFactory::new("YOUR_API_KEY");
let devnet_client = factory.create(Cluster::Devnet)?;
let mainnet_client = factory.create(Cluster::MainnetBeta)?;

访问嵌入式Solana客户端

helius.connection()          // Sync SolanaRpcClient (Arc)
helius.async_connection()?   // Async SolanaRpcClient (requires new_async or HeliusBuilder)
helius.ws()                  // Enhanced WebSocket (Option)
helius.rpc()                 // Helius RpcClient (Arc)
helius.config()              // Config (Arc)

对代理的建议

使用get_transactions_for_address而不是两步查找

get_transactions_for_address将签名查找和交易获取合并为一次调用,并在服务器端进行过滤。
// GOOD: Single call, server-side filtering
let txs = helius.rpc().get_transactions_for_address(
    "address".to_string(),
    GetTransactionsForAddressOptions {
        transaction_details: Some(TransactionDetails::Full),
        limit: Some(100),
        filters: Some(GetTransactionsFilters {
            token_accounts: Some(TokenAccountsFilter::BalanceChanged),
            ..Default::default()
        }),
        ..Default::default()
    },
).await?;

// BAD: Two calls, client-side filtering
let sigs = helius.connection().get_signatures_for_address(&address)?;

对标准发送使用send_smart_transaction

它会自动模拟、估算计算单元、获取优先费用并确认。不要手动构建ComputeBudget指令——SDK会自动添加它们。
let sig = helius.send_smart_transaction(SmartTransactionConfig {
    create_config: CreateSmartTransactionConfig {
        instructions: vec![your_instruction],
        signers: vec![wallet_signer],
        priority_fee_cap: Some(100_000),
        cu_buffer_multiplier: Some(1.1),
        ..Default::default()
    },
    ..Default::default()
}).await?;

使用Helius Sender以实现超低延迟

对于时间敏感的交易(套利、狙击、清算),使用send_smart_transaction_with_sender。它通过Helius的多区域基础设施和Jito进行路由。
let sig = helius.send_smart_transaction_with_sender(
    SmartTransactionConfig {
        create_config: CreateSmartTransactionConfig {
            instructions: vec![your_instruction],
            signers: vec![wallet_signer],
            ..Default::default()
        },
        ..Default::default()
    },
    SenderSendOptions {
        region: "US_EAST".to_string(),    // Default, US_SLC, US_EAST, EU_WEST, EU_CENTRAL, EU_NORTH, AP_SINGAPORE, AP_TOKYO
        swqos_only: false,                // true = SWQOS only (lower tip), false = Dual (SWQOS + Jito)
        poll_timeout_ms: 60_000,
        poll_interval_ms: 2_000,
    },
).await?;

对多个资产使用get_asset_batch

在获取多个资产时,将它们批处理。不要在循环中调用get_asset
// GOOD: Single request
let assets = helius.rpc().get_asset_batch(GetAssetBatch {
    ids: vec!["mint1".to_string(), "mint2".to_string(), "mint3".to_string()],
    ..Default::default()
}).await?;

// BAD: N requests
for id in mints {
    let asset = helius.rpc().get_asset(GetAsset { id, ..Default::default() }).await?;
}

使用webhooks代替轮询

不要在循环中轮询get_transactions_for_address。使用webhooks进行服务器到服务器的通知。
let webhook = helius.create_webhook(CreateWebhookRequest {
    webhook_url: "https://your-server.com/webhook".to_string(),
    webhook_type: WebhookType::Enhanced,
    transaction_types: vec![TransactionType::Transfer, TransactionType::NftSale, TransactionType::Swap],
    account_addresses: vec!["address_to_monitor".to_string()],
    auth_header: Some("Bearer your-secret".to_string()),
    ..Default::default()
}).await?;

分页

基于Token/Cursor(RPC V2方法)

// get_transactions_for_address uses pagination_token
let mut pagination_token: Option<String> = None;
let mut all_txs = Vec::new();
loop {
    let result = helius.rpc().get_transactions_for_address(
        "address".to_string(),
        GetTransactionsForAddressOptions {
            limit: Some(100),
            pagination_token: pagination_token.clone(),
            ..Default::default()
        },
    ).await?;
    all_txs.extend(result.data);
    pagination_token = result.pagination_token;
    if pagination_token.is_none() { break; }
}

// Or use auto-paginating variants:
let all_accounts = helius.rpc().get_all_program_accounts(
    program_id.to_string(),
    GetProgramAccountsV2Config::default(),
).await?;

基于页面(DAS API)

let mut page = 1;
let mut all_assets = Vec::new();
loop {
    let result = helius.rpc().get_assets_by_owner(GetAssetsByOwner {
        owner_address: "...".to_string(),
        page,
        limit: Some(1000),
        ..Default::default()
    }).await?;
    let count = result.items.len();
    all_assets.extend(result.items);
    if count < 1000 { break; }
    page += 1;
}

token_accounts过滤器

查询get_transactions_for_address时,token_accounts过滤器控制是否包含代币账户活动:
Value行为适用场景
None仅包括直接涉及该地址的交易仅关心 SOL 转账和程序调用时使用
BalanceChanged还包括改变余额的代币交易建议大多数代理使用 — 显示代币发送/接收而无杂音
All包括所有代币账户交易需要完整的代币活动时使用(可能返回大量结果)

changed_since_slot — 增量账户获取

changed_since_slot 仅返回在给定 slot 后修改的账户。适用于同步或索引工作流程。由 get_program_accounts_v2get_token_accounts_by_owner_v2get_account_infoget_multiple_accountsget_program_accountsget_token_accounts_by_owner 支持。
// First fetch: get all accounts
let baseline = helius.rpc().get_program_accounts_v2(
    program_id.to_string(),
    GetProgramAccountsV2Config { limit: Some(10_000), ..Default::default() },
).await?;
let last_slot = current_slot;

// Later: only get accounts that changed since your last fetch
let updates = helius.rpc().get_program_accounts_v2(
    program_id.to_string(),
    GetProgramAccountsV2Config {
        limit: Some(10_000),
        changed_since_slot: Some(last_slot),
        ..Default::default()
    },
).await?;

常见错误

  1. transaction_details: Some(TransactionDetails::Full) 不是默认值 — 默认情况下,get_transactions_for_address 仅返回签名。设置 TransactionDetails::Full 获取完整的交易数据。
  2. 不要使用 send_smart_transaction 添加 ComputeBudget 指令 — SDK 会自动添加。自己添加会导致 HeliusError::InvalidInput 错误。
  3. 优先费用以每计算单元的微 lamports 为单位 — 不是 lamports。get_priority_fee_estimate 的值已经是正确的单位。
  4. DAS 分页从 1 开始page: 1 是第一页,不是 page: 0
  5. async_connection() 需要 new_asyncHeliusBuilder — 在用 Helius::new() 创建的客户端上调用 helius.async_connection() 会返回 Err(HeliusError::ClientNotInitialized)
  6. get_asset 返回 Option<Asset> — 如果资产不存在,成功的响应可能仍然是 None。需要显式处理 Option
  7. 发送者的小费是强制的send_smart_transaction_with_sender 自动确定并追加小费。最低 0.0002 SOL(双模式)或 0.000005 SOL(仅 SWQOS)。
  8. TLS 功能标志 — crate 默认使用 native-tls。当 OpenSSL 不可用时,使用 features = ["rustls"](和 default-features = false)提供纯 Rust TLS。

错误处理和重试

SDK通过HeliusError枚举提供类型化错误变体,因此您可以直接匹配它们:
use helius::error::{HeliusError, Result};

match helius.rpc().get_asset(request).await {
    Ok(asset) => { /* success */ }
    Err(HeliusError::Unauthorized { .. }) => { /* 401: invalid or missing API key */ }
    Err(HeliusError::RateLimitExceeded { .. }) => { /* 429: too many requests or out of credits */ }
    Err(HeliusError::InternalError { .. }) => { /* 5xx: server error, retry with backoff */ }
    Err(HeliusError::NotFound { .. }) => { /* 404: resource not found */ }
    Err(HeliusError::BadRequest { .. }) => { /* 400: malformed request */ }
    Err(HeliusError::Timeout { .. }) => { /* transaction confirmation timed out */ }
    Err(e) => { /* other errors: Network, SerdeJson, etc. */ }
}

重试策略

RateLimitExceededInternalError进行指数退避重试:
async fn with_retry<T, F, Fut>(f: F, max_retries: u32) -> Result<T>
where
    F: Fn() -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    for attempt in 0..=max_retries {
        match f().await {
            Ok(val) => return Ok(val),
            Err(HeliusError::RateLimitExceeded { .. })
            | Err(HeliusError::InternalError { .. }) if attempt < max_retries => {
                tokio::time::sleep(std::time::Duration::from_millis(1000 * 2u64.pow(attempt))).await;
            }
            Err(e) => return Err(e),
        }
    }
    unreachable!()
}
错误变体HTTP 状态操作
Unauthorized401检查 API 密钥
RateLimitExceeded429退避并重试
InternalError5xx指数退避重试
BadRequest400修复请求参数
NotFound404检查资源是否存在
Timeout增加超时或重试

API 快速参考

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

DAS API(数字资产标准)

helius.rpc().get_asset(GetAsset { id, .. })                              // Single asset by mint
helius.rpc().get_asset_batch(GetAssetBatch { ids, .. })                  // Multiple assets
helius.rpc().get_assets_by_owner(GetAssetsByOwner { owner_address, .. }) // Assets by wallet
helius.rpc().get_assets_by_authority(GetAssetsByAuthority { .. })        // Assets by update authority
helius.rpc().get_assets_by_creator(GetAssetsByCreator { .. })            // Assets by creator
helius.rpc().get_assets_by_group(GetAssetsByGroup { .. })                // Assets by collection
helius.rpc().search_assets(SearchAssets { .. })                          // Flexible search
helius.rpc().get_asset_proof(GetAssetProof { id })                       // Merkle proof (cNFTs)
helius.rpc().get_asset_proof_batch(GetAssetProofBatch { ids })           // Batch Merkle proofs
helius.rpc().get_token_accounts(GetTokenAccounts { .. })                 // Token accounts
helius.rpc().get_nft_editions(GetNftEditions { .. })                     // Print editions
helius.rpc().get_signatures_for_asset(GetAssetSignatures { id, .. })     // Transaction history for asset

RPC V2 方法

helius.rpc().get_transactions_for_address(address, options)              // Transaction history (pagination_token)
helius.rpc().get_program_accounts_v2(program_id, config)                 // Program accounts (pagination_key)
helius.rpc().get_all_program_accounts(program_id, config)                // Auto-paginating variant
helius.rpc().get_token_accounts_by_owner_v2(owner, filter, config)       // Token accounts v2 (pagination_key)
helius.rpc().get_all_token_accounts_by_owner(owner, filter, config)      // Auto-paginating variant
helius.rpc().get_priority_fee_estimate(request)                          // Fee estimates

智能交易和Helius Sender

helius.send_smart_transaction(config)                                    // Auto-optimized send
helius.create_smart_transaction(config)                                  // Build without sending
helius.create_smart_transaction_with_seeds(config)                       // Thread-safe (seed-based)
helius.send_smart_transaction_with_seeds(config, send_opts, timeout)     // Thread-safe send
helius.send_smart_transaction_with_sender(config, sender_opts)           // Build + send via Sender
helius.create_smart_transaction_with_tip_for_sender(config, tip)         // Build with tip
helius.send_and_confirm_via_sender(tx, last_block, sender_opts)          // Send pre-built tx via Sender
helius.determine_tip_lamports(swqos_only)                                // Calculate tip amount
helius.fetch_tip_floor_75th()                                            // Get Jito tip floor
helius.warm_sender_connection(region)                                    // Warm connection via /ping
helius.get_compute_units(instructions, payer, lookup_tables, signers)    // Simulate CU usage
helius.poll_transaction_confirmation(signature)                          // Poll confirmation status

增强型交易

helius.parse_transactions(ParseTransactionsRequest { transactions })     // Parse by signatures
helius.parsed_transaction_history(ParsedTransactionHistoryRequest { .. })// Parse by address

Webhooks

helius.create_webhook(CreateWebhookRequest { .. })                       // Create webhook
helius.get_webhook_by_id(webhook_id)                                     // Get webhook config
helius.get_all_webhooks()                                                // List all webhooks
helius.edit_webhook(EditWebhookRequest { .. })                           // Update webhook
helius.delete_webhook(webhook_id)                                        // Delete webhook
helius.append_addresses_to_webhook(webhook_id, &addresses)               // Add monitored addresses
helius.remove_addresses_from_webhook(webhook_id, &addresses)             // Remove monitored addresses

Wallet API

helius.get_wallet_identity(wallet)                                       // Identity info
helius.get_batch_wallet_identity(&addresses)                             // Batch identity (max 100)
helius.get_wallet_balances(wallet, page, limit, zero_bal, native, nfts)  // Token balances
helius.get_wallet_history(wallet, limit, before, after, tx_type, token_accts)  // Transaction history
helius.get_wallet_transfers(wallet, limit, cursor)                       // Transfer history
helius.get_wallet_funding_source(wallet)                                 // Funding source

Staking

helius.create_stake_transaction(owner, amount_sol)                       // Create + delegate stake
helius.create_unstake_transaction(owner, stake_account)                  // Deactivate stake
helius.create_withdraw_transaction(owner, stake_acct, dest, lamports)    // Withdraw
helius.get_stake_instructions(owner, amount_sol)                         // Get raw instructions + keypair
helius.get_unstake_instruction(owner, stake_account)                     // Deactivate instruction
helius.get_withdraw_instruction(owner, stake_acct, dest, lamports)       // Withdraw instruction
helius.get_withdrawable_amount(stake_account, include_rent_exempt)       // Check withdrawable balance
helius.get_stake_accounts(wallet)                                        // List stake accounts

嵌入式 Solana 客户端

helius.connection()                  // Sync SolanaRpcClient (Arc)
helius.async_connection()?           // Async SolanaRpcClient (requires new_async)
helius.ws()                          // Enhanced WebSocket (Option)

// Standard Solana RPC via embedded client
let balance = helius.connection().get_balance(&pubkey)?;
let async_client = helius.async_connection()?;
let balance = async_client.get_balance(&pubkey).await?;

资源