跳转到主要内容

Documentation Index

Fetch the complete documentation index at: https://docs.orbitflare.com/llms.txt

Use this file to discover all available pages before exploring further.

安装

npm install @orbitflare/sdk
RPC 客户端无额外的对等依赖。

构建客户端

以下示例启用全部选项:
import { RpcClientBuilder, type RetryPolicy } from '@orbitflare/sdk';

const client = new RpcClientBuilder()
  .url('http://ny.rpc.orbitflare.com')
  .fallbackUrl('http://fra.rpc.orbitflare.com')
  .fallbackUrl('http://ams.rpc.orbitflare.com')
  .apiKey('ORBIT-XXXXXX-NNNNNN-NNNNNN')
  .commitment('confirmed')
  .retry({
    initialDelayMs: 100,
    maxDelayMs: 30_000,
    multiplier: 2.0,
    maxAttempts: 5,
  })
  .timeoutMs(30_000)
  .build();
大多数选项都有合理默认值。最简配置:
const client = new RpcClientBuilder()
  .url('http://ny.rpc.orbitflare.com')
  .build();

构建器方法

.url(url) - 发送请求的主端点。若未设置,SDK 会读取环境变量 ORBITFLARE_RPC_URL
.url('http://ny.rpc.orbitflare.com')
.urls([...]) - 一次设置主端点与所有备用端点。第一个元素为主端点,其余为备用。
.urls(['http://ny.rpc.orbitflare.com', 'http://fra.rpc.orbitflare.com', 'http://ams.rpc.orbitflare.com'])
.fallbackUrl(url) - 添加单个备用端点。可多次调用以添加多个。主端点失败时,SDK 按顺序尝试备用端点。
.fallbackUrl('http://fra.rpc.orbitflare.com')
.fallbackUrl('http://ams.rpc.orbitflare.com')
.fallbackUrls([...]) - 与 fallbackUrl 相同,但接受数组。
.fallbackUrls(['http://fra.rpc.orbitflare.com', 'http://ams.rpc.orbitflare.com'])
.apiKey(key) - OrbitFlare 许可证密钥。若未设置,SDK 从环境读取 ORBITFLARE_LICENSE_KEY。密钥在请求时注入 URL,不会存储在端点字符串中。
.apiKey('ORBIT-XXXXXX-NNNNNN-NNNNNN')
.commitment(level) - 所有类型化辅助方法的默认承诺级别。可选:'processed''confirmed''finalized'。默认为 'confirmed'
.commitment('finalized')
.retry(policy) - 控制失败请求的重试策略。initialDelayMs 为首次重试前等待时间。multiplier 为每次尝试的延迟倍数。maxDelayMs 为退避上限。maxAttempts 限制每个端点的总重试次数(0 表示无限)。默认:初始 100ms、最大 30s、2 倍乘数、无限次尝试。
.retry({
  initialDelayMs: 200,
  maxDelayMs: 15_000,
  multiplier: 2.0,
  maxAttempts: 5,
})
.timeoutMs(ms) - 单次 HTTP 请求超时。默认 30 秒。
.timeoutMs(10_000)

可用 RPC 方法

getSlot()

返回当前槽位号。
const slot: number = await client.getSlot();

getBalance(address)

返回账户余额(lamports)。
const lamports: number = await client.getBalance('So11111111111111111111111111111111111111112');
const sol = lamports / 1_000_000_000;

getAccountInfo(address)

返回完整账户数据;若账户不存在则返回 null。数据为 base64 编码。
const account = await client.getAccountInfo('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
if (account) {
  console.log('owner:', account.owner);
  console.log('lamports:', account.lamports);
  console.log('data length:', (account.data?.[0] ?? '').length);
}

getMultipleAccounts(addresses)

一次调用获取多个账户。自动按每批 100 个地址分块(Solana 单次请求限制),因此可传入任意数量地址。
const accounts = await client.getMultipleAccounts(['addr1', 'addr2', 'addr3']);

accounts.forEach((acct, i) => {
  if (acct) console.log(`account ${i}: ${acct.lamports} lamports`);
  else console.log(`account ${i}: not found`);
});

getLatestBlockhash()

返回最新区块哈希及其有效截止的最后区块高度。
const { blockhash, lastValidBlockHeight } = await client.getLatestBlockhash();

getTransaction(signature)

按签名拉取已确认交易。返回含元数据的完整交易。
const tx = await client.getTransaction('5K8F2j...');
console.log('slot:', tx.slot);
console.log('fee:', tx.meta?.fee);

getSignaturesForAddress(address, limit)

返回某地址的最近交易签名,按时间从新到旧。
const sigs = await client.getSignaturesForAddress('So111...', 10);

for (const sig of sigs) {
  console.log(`${sig.signature} at slot ${sig.slot}`);
}

getProgramAccounts(programId)

返回某程序拥有的全部账户。可能返回大量数据。
const accounts = await client.getProgramAccounts('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');

getRecentPrioritizationFees(addresses)

返回一组账户的近期优先费用样本。可用于估算计算单元定价。
const fees = await client.getRecentPrioritizationFees(['6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P']);

for (const fee of fees) {
  console.log(`slot ${fee.slot}: ${fee.prioritizationFee} micro-lamports`);
}

sendTransaction(txBase64)

向网络提交已签名交易。参数为 base64 序列化交易。返回交易签名。
const signature: string = await client.sendTransaction(txBase64);
console.log('sent:', signature);

simulateTransaction(txBase64)

模拟交易而不提交。返回日志、消耗的计算单元及任何错误。
const result = await client.simulateTransaction(txBase64);
if (result.err) {
  console.log('simulation failed:', result.err);
} else {
  console.log('compute units:', result.unitsConsumed);
}

getTokenAccountsByOwner(owner, mint?, programId?)

返回钱包的代币账户。可传入特定 mint 或代币程序 ID。若两者均省略,默认使用 SPL Token 程序。
const tokens = await client.getTokenAccountsByOwner('wallet_address');

for (const token of tokens) {
  const info = token.account?.data?.parsed?.info;
  console.log(`mint: ${info?.mint} balance: ${info?.tokenAmount?.uiAmountString}`);
}

getTransactionsForAddress(address, options)

OrbitFlare 特有方法:将 getSignaturesForAddressgetTransaction 合并为一次调用。返回 GetTransactionsResult,包含 data 数组及用于下一页的可选 paginationToken 支持四种详情级别(signaturesnoneaccountsfull)、双向排序、时间/槽位过滤、状态过滤及代币账户包含选项。
const result = await client.getTransactionsForAddress('address', {
  transactionDetails: 'full',
  limit: 100,
  sortOrder: 'asc',
  filters: {
    tokenAccounts: 'all',
    status: 'succeeded',
    blockTime: { gte: 1704067200, lte: 1706745600 },
  },
});

for (const tx of result.data) {
  console.log(`slot ${tx.slot}`);
}

if (result.paginationToken) {
  // fetch next page using { paginationToken: result.paginationToken }
}

request(method, params)

按名称调用任意 RPC 方法。SDK 构建 JSON-RPC 信封,处理重试与故障转移,并返回 result 字段。
const epoch = await client.request('getEpochInfo', []);
const inflation = await client.request('getInflationRate', []);
const supply = await client.request('getSupply', []);

requestRaw(body)

发送原始 JSON-RPC 请求体字符串。重试与故障转移行为与其他方法相同。
const result = await client.requestRaw(
  '{"jsonrpc":"2.0","id":1,"method":"getHealth","params":[]}',
);

完整示例

以下脚本检查网络状态、查询钱包 SOL 余额与代币持仓,并查看最近交易。
import { RpcClientBuilder } from '@orbitflare/sdk';

async function main() {
  const client = new RpcClientBuilder()
    .url('http://ny.rpc.orbitflare.com')
    .fallbackUrl('http://fra.rpc.orbitflare.com')
    .commitment('confirmed')
    .build();

  const wallet = 'CKs1E69a2e9TmH4mKKLrXFF8kD3ZnwKjoEuXa6sz9WqX';

  const slot = await client.getSlot();
  const { blockhash } = await client.getLatestBlockhash();
  console.log(`network slot: ${slot}`);
  console.log(`blockhash: ${blockhash}`);

  const balance = await client.getBalance(wallet);
  console.log(`\n${wallet}`);
  console.log(`  SOL: ${(balance / 1_000_000_000).toFixed(4)}`);

  const tokens = await client.getTokenAccountsByOwner(wallet);
  for (const token of tokens) {
    const info = token?.account?.data?.parsed?.info;
    const mint = info?.mint ?? 'unknown';
    const amount = info?.tokenAmount?.uiAmountString ?? '0';
    if (amount !== '0') console.log(`  ${mint}: ${amount}`);
  }

  const sigs = await client.getSignaturesForAddress(wallet, 5);
  console.log('\nrecent transactions:');
  for (const sig of sigs) {
    const signature = sig?.signature ?? '?';
    const status = sig?.err == null ? 'ok' : 'failed';
    console.log(`  ${sig?.slot ?? 0} ${status} ${signature.slice(0, 20)}`);
  }

  const fees = await client.getRecentPrioritizationFees([wallet]);
  const total = fees.reduce(
    (acc: number, f: any) =>
      acc + (typeof f?.prioritizationFee === 'number' ? f.prioritizationFee : 0),
    0,
  );
  const avg = total / Math.max(fees.length, 1);
  console.log(`\navg priority fee: ${avg.toFixed(0)} micro-lamports`);
}

void main();