> ## Documentation Index
> Fetch the complete documentation index at: https://www.helius.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Solana RPC 最適化: パフォーマンスとコストのベストプラクティス

> Solana RPC のパフォーマンスを最適化し、コストを削減し、信頼性を向上させます。トランザクション最適化、データ取得パターン、ベストプラクティスガイド。

RPC の使用を最適化することで、パフォーマンスが大幅に向上し、コストが削減され、ユーザーエクスペリエンスが向上します。このガイドでは、効率的な Solana RPC のやり取りのための証明された技術を紹介します。

## クイックスタート

<CardGroup cols={2}>
  <Card title="トランザクション最適化" icon="bolt" href="#transaction-optimization">
    コンピュートユニット、優先料金、トランザクション送信を最適化
  </Card>

  <Card title="データ取得" icon="database" href="#data-retrieval-optimization">
    アカウントとプログラムデータを効率的に取得するパターン
  </Card>

  <Card title="リアルタイムモニタリング" icon="chart-line" href="#real-time-monitoring">
    WebSocket サブスクリプションとストリーミングデータの最適化
  </Card>

  <Card title="ベストプラクティス" icon="shield-check" href="#best-practices">
    パフォーマンスガイドラインとリソース管理
  </Card>
</CardGroup>

## トランザクション最適化

### コンピュートユニット管理

**1. 実際の使用量を判断するためにシミュレートする:**

```typescript theme={"system"}
const testTransaction = new VersionedTransaction(/* your transaction */);
const simulation = await connection.simulateTransaction(testTransaction, {
  replaceRecentBlockhash: true,
  sigVerify: false
});
const unitsConsumed = simulation.value.unitsConsumed;
```

**2. マージンを持たせて適切な制限を設定する:**

```typescript theme={"system"}
const computeUnitLimit = Math.ceil(unitsConsumed * 1.1);
const computeUnitIx = ComputeBudgetProgram.setComputeUnitLimit({ 
  units: computeUnitLimit 
});
instructions.unshift(computeUnitIx); // Add at beginning
```

### 優先料金の最適化

**1. 動的料金見積もりを取得する:**

```typescript theme={"system"}
const response = await fetch(`https://mainnet.helius-rpc.com/?api-key=${API_KEY}`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    method: 'getPriorityFeeEstimate',
    params: [{
      accountKeys: ['11111111111111111111111111111112'], // System Program
      options: { recommended: true }
    }]
  })
});
const { priorityFeeEstimate } = await response.json().result;
```

**2. 優先料金を適用する:**

```typescript theme={"system"}
const priorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({ 
  microLamports: priorityFeeEstimate 
});
instructions.unshift(priorityFeeIx);
```

### トランザクション送信のベストプラクティス

<Tabs>
  <Tab title="標準的なアプローチ">
    ```typescript theme={"system"}
    // Serialize and encode
    const serializedTx = transaction.serialize();
    const signature = await connection.sendRawTransaction(serializedTx, {
      skipPreflight: true, // Saves ~100ms
      maxRetries: 0 // Handle retries manually
    });
    ```
  </Tab>

  <Tab title="確認付き">
    ```typescript theme={"system"}
    // Send and confirm with custom logic
    const signature = await connection.sendRawTransaction(serializedTx);

    // Monitor confirmation
    const confirmation = await connection.confirmTransaction({
      signature,
      blockhash: latestBlockhash.blockhash,
      lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
    });
    ```
  </Tab>
</Tabs>

## データ取得の最適化

### 強化されたページネーションメソッド (V2)

**大規模なデータクエリには、新しい V2 メソッドをカーソルベースのページネーションで使用します:**

<Card title="⚡ パフォーマンス向上" icon="rocket" color="#E84125">
  `getProgramAccountsV2` と `getTokenAccountsByOwnerV2` は大規模データセットを扱うアプリケーションに重大なパフォーマンス改善を提供します:

  * **設定可能な制限**: リクエストあたり1-10,000アカウント
  * **カーソルベースのページネーション**: 大規模クエリでのタイムアウトを防止
  * **インクリメンタル更新**: リアルタイム同期には `changedSinceSlot` を使用
  * **メモリ使用の改善**: 全てを一度に読み込む代わりにデータをストリームする
</Card>

**例: 効率的なプログラムアカウントクエリ**

```typescript theme={"system"}
// ❌ Old approach - could timeout with large datasets
const allAccounts = await connection.getProgramAccounts(programId, {
  encoding: 'base64',
  filters: [{ dataSize: 165 }]
});

// ✅ New approach - paginated with better performance
let allAccounts = [];
let paginationKey = null;

do {
  const response = await fetch(`https://mainnet.helius-rpc.com/?api-key=${API_KEY}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: '1',
      method: 'getProgramAccountsV2',
      params: [
        programId,
        {
          encoding: 'base64',
          filters: [{ dataSize: 165 }],
          limit: 5000,
          ...(paginationKey && { paginationKey })
        }
      ]
    })
  });
  
  const data = await response.json();
  allAccounts.push(...data.result.accounts);
  paginationKey = data.result.paginationKey;
} while (paginationKey);
```

**リアルタイムアプリケーションのためのインクリメンタル更新:**

```typescript theme={"system"}
// Get only accounts modified since a specific slot
const incrementalUpdate = await fetch(`https://mainnet.helius-rpc.com/?api-key=${API_KEY}`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: '1',
    method: 'getProgramAccountsV2',
    params: [
      programId,
      {
        encoding: 'jsonParsed',
        limit: 1000,
        changedSinceSlot: lastProcessedSlot // Only get recent changes
      }
    ]
  })
});
```

## データ取得最適化

### 効率的なアカウントクエリ

<Tabs>
  <Tab title="シングルアカウント">
    ```typescript theme={"system"}
    // Use dataSlice to reduce payload size
    const accountInfo = await connection.getAccountInfo(pubkey, {
      encoding: 'base64',
      dataSlice: { offset: 0, length: 100 }, // Only get needed data
      commitment: 'confirmed'
    });
    ```
  </Tab>

  <Tab title="複数アカウント">
    ```typescript theme={"system"}
    // Batch multiple account queries
    const accounts = await connection.getMultipleAccountsInfo([
      pubkey1, pubkey2, pubkey3
    ], {
      encoding: 'base64',
      commitment: 'confirmed'
    });
    ```
  </Tab>

  <Tab title="プログラムアカウント">
    ```typescript theme={"system"}
    // Use filters to reduce data transfer
    const accounts = await connection.getProgramAccounts(programId, {
      filters: [
        { dataSize: 165 }, // Token account size
        { memcmp: { offset: 0, bytes: mintAddress }}
      ],
      encoding: 'jsonParsed'
    });
    ```
  </Tab>
</Tabs>

### トークン残高の確認

<CodeGroup>
  ```typescript ❌ Inefficient theme={"system"}
  // Don't do this - requires N+1 RPC calls
  const tokenAccounts = await connection.getTokenAccountsByOwner(owner, {
    programId: TOKEN_PROGRAM_ID
  });
  const balances = await Promise.all(
    tokenAccounts.value.map(acc => 
      connection.getTokenAccountBalance(acc.pubkey)
    )
  );
  // ~500ms + (100ms * N accounts)
  ```

  ```typescript ✅ Optimized theme={"system"}
  // Single call with parsed data
  const tokenAccounts = await connection.getTokenAccountsByOwner(owner, {
    programId: TOKEN_PROGRAM_ID
  }, { encoding: 'jsonParsed' });

  const balances = tokenAccounts.value.map(acc => ({
    mint: acc.account.data.parsed.info.mint,
    amount: acc.account.data.parsed.info.tokenAmount.uiAmount
  }));
  // ~500ms total - 95% reduction for large wallets
  ```
</CodeGroup>

### トランザクション履歴

完全なアドレス履歴を得るには、アドレス専用の [`getTransactionsForAddress`](/ja/rpc/gettransactionsforaddress) メソッドを使います。この方法は、トークンのアカウント活動を含む完全なトランザクションデータを一度に返します（Helius専用）。

<CodeGroup>
  ```typescript ❌ Inefficient theme={"system"}
  // Avoid sequential transaction fetching
  const signatures = await connection.getSignaturesForAddress(address, { limit: 100 });
  const transactions = await Promise.all(
    signatures.map(sig => connection.getTransaction(sig.signature))
  );
  // ~1s + (200ms * 100 txs) = ~21s
  // Also note: getSignaturesForAddress doesn't include token account transactions
  ```

  ```typescript ✅ Fast (Helius Exclusive) theme={"system"}
  // Use getTransactionsForAddress for full history including token accounts
  const response = await fetch(`https://mainnet.helius-rpc.com/?api-key=${API_KEY}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'getTransactionsForAddress',
      params: [
        address,
        {
          transactionDetails: 'full',
          limit: 100,
          filters: { tokenAccounts: 'balanceChanged' }
        }
      ]
    })
  });
  // ~100ms total - includes complete token history in one call
  ```
</CodeGroup>

### 送金履歴

トークンやSOLの動きだけが必要な場合 - 支払い、ポートフォリオ活動、バランス調整 - は、[`getTransfersByAddress`](/ja/rpc/gettransfersbyaddress) を使用します（Helius専用、[Developer プラン](/ja/billing/plans)以上が必要）。これは、オーナー、ミント、量、桁数が解決された解析済みの転送オブジェクトを返すため、トランザクションの解析を完全にスキップできます。

```typescript theme={"system"}
// Parsed USDC transfers received by a wallet - no manual parsing needed
const response = await fetch(`https://mainnet.helius-rpc.com/?api-key=${API_KEY}`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'getTransfersByAddress',
    params: [
      address, // Wallet owner address, not a token account
      {
        mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
        direction: 'in',
        limit: 100
      }
    ]
  })
});
// Each transfer includes parsed sender, recipient, amount, decimals, and uiAmount
```

指針: 完全なトランザクションペイロードや非転送活動が必要な場合は `getTransactionsForAddress` を、台帳や支払い追跡のためのクリーンな転送記録が必要な場合は `getTransfersByAddress` を使用してください。

## リアルタイムモニタリング

### アカウントサブスクリプション

<CodeGroup>
  ```typescript ❌ Polling theme={"system"}
  // Avoid polling - wastes resources
  setInterval(async () => {
    const accountInfo = await connection.getAccountInfo(pubkey);
    // Process updates...
  }, 1000);
  ```

  ```typescript ✅ WebSocket theme={"system"}
  // Use WebSocket subscriptions for real-time updates
  const subscriptionId = connection.onAccountChange(
    pubkey,
    (accountInfo, context) => {
      // Handle real-time updates
      console.log('Account updated:', accountInfo);
    },
    'confirmed',
    { encoding: 'base64', dataSlice: { offset: 0, length: 100 }}
  );
  ```
</CodeGroup>

### プログラムアカウントのモニタリング

```typescript theme={"system"}
// Monitor specific program accounts with filters
connection.onProgramAccountChange(
  programId,
  (accountInfo, context) => {
    // Handle program account changes
  },
  'confirmed',
  {
    filters: [
      { dataSize: 1024 },
      { memcmp: { offset: 0, bytes: ACCOUNT_DISCRIMINATOR }}
    ],
    encoding: 'base64'
  }
);
```

### トランザクションモニタリング

```typescript theme={"system"}
// Subscribe to transaction logs for real-time monitoring
const ws = new WebSocket(`wss://mainnet.helius-rpc.com/?api-key=${API_KEY}`);

ws.on('open', () => {
  ws.send(JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'logsSubscribe',
    params: [
      { mentions: [programId] },
      { commitment: 'confirmed' }
    ]
  }));
});

ws.on('message', (data) => {
  const message = JSON.parse(data);
  if (message.params) {
    const signature = message.params.result.value.signature;
    // Process transaction signature
  }
});
```

## 高度なパターン

### スマート再試行ロジック

```typescript theme={"system"}
class RetryManager {
  private backoff = new ExponentialBackoff({
    min: 100,
    max: 5000,
    factor: 2,
    jitter: 0.2
  });

  async executeWithRetry<T>(operation: () => Promise<T>): Promise<T> {
    while (true) {
      try {
        return await operation();
      } catch (error) {
        if (error.message.includes('429')) {
          // Rate limit - wait and retry
          await this.backoff.delay();
          continue;
        }
        throw error;
      }
    }
  }
}
```

### メモリ効率の良い処理

```typescript theme={"system"}
// Process large datasets in chunks
function chunk<T>(array: T[], size: number): T[][] {
  return Array.from({ length: Math.ceil(array.length / size) }, (_, i) =>
    array.slice(i * size, i * size + size)
  );
}

// Process program accounts in batches
const allAccounts = await connection.getProgramAccounts(programId, {
  dataSlice: { offset: 0, length: 32 }
});

const chunks = chunk(allAccounts, 100);
for (const batch of chunks) {
  const detailedAccounts = await connection.getMultipleAccountsInfo(
    batch.map(acc => acc.pubkey)
  );
  // Process batch...
}
```

### 接続プーリング

```typescript theme={"system"}
class ConnectionPool {
  private connections: Connection[] = [];
  private currentIndex = 0;

  constructor(rpcUrls: string[]) {
    this.connections = rpcUrls.map(url => new Connection(url));
  }

  getConnection(): Connection {
    const connection = this.connections[this.currentIndex];
    this.currentIndex = (this.currentIndex + 1) % this.connections.length;
    return connection;
  }
}

const pool = new ConnectionPool([
  'https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY',
  'https://mainnet-backup.helius-rpc.com/?api-key=YOUR_API_KEY'
]);
```

## パフォーマンスモニタリング

### RPC使用量の追跡

```typescript theme={"system"}
class RPCMonitor {
  private metrics = {
    calls: 0,
    errors: 0,
    totalLatency: 0
  };

  async monitoredCall<T>(operation: () => Promise<T>): Promise<T> {
    const start = Date.now();
    this.metrics.calls++;
    
    try {
      const result = await operation();
      this.metrics.totalLatency += Date.now() - start;
      return result;
    } catch (error) {
      this.metrics.errors++;
      throw error;
    }
  }

  getStats() {
    return {
      ...this.metrics,
      averageLatency: this.metrics.totalLatency / this.metrics.calls,
      errorRate: this.metrics.errors / this.metrics.calls
    };
  }
}
```

## ベストプラクティス

### コミットメントレベル

<Tabs>
  <Tab title="処理済み">
    * **使用対象**: WebSocket サブスクリプション、リアルタイム更新
    * **レイテンシー**: 約400ms
    * **信頼性**: ほとんどのアプリケーションにとって良好
  </Tab>

  <Tab title="確認済み">
    * **使用対象**: 一般的なクエリ、アカウント情報
    * **レイテンシー**: 約1秒
    * **信頼性**: ほとんどの使用ケースに推奨
  </Tab>

  <Tab title="確定済み">
    * **使用対象**: 最終決済、不可逆操作
    * **レイテンシー**: 約32秒
    * **信頼性**: 最大の確実性
  </Tab>
</Tabs>

### リソース管理

<CheckboxList>
  * `dataSlice` を使用してペイロードサイズを制限する
  * サーバー側フィルタリングを `memcmp` と `dataSize` で実装する
  * ラウンドトリップを減らすためにバッチ操作を行う
  * 冗長な呼び出しを避けるために結果をキャッシュする
  * 完了時に WebSocket サブスクリプションを閉じる
  * エラーハンドリングのためにサーキットブレーカーを実装する
</CheckboxList>

### エラーハンドリング

```typescript theme={"system"}
// Implement robust error handling
async function robustRPCCall<T>(operation: () => Promise<T>): Promise<T> {
  try {
    return await operation();
  } catch (error) {
    if (error.code === -32602) {
      // Invalid params - fix request
      throw new Error('Invalid RPC parameters');
    } else if (error.code === -32005) {
      // Node behind - retry with different node
      throw new Error('Node synchronization issue');
    } else if (error.message.includes('429')) {
      // Rate limit - implement backoff
      throw new Error('Rate limited');
    }
    throw error;
  }
}
```

## 避けるべき一般的な落とし穴

<Warning>
  **以下の一般的な間違いを避けてください:**

  * WebSocket サブスクリプションを使わずにポーリングする
  * 必要な部分データのみで全体のアカウントデータを取得する
  * 複数のクエリに対してバッチ操作を使用しない
  * レート制限を無視し、適切な再試行ロジックを実装しない
  * `finalized` コミットメントを使用する場合に、`confirmed` が十分
  * サブスクリプションを閉じずにメモリリークを引き起こす
</Warning>

## 関連メソッド

このガイドで取り上げた最適化技術は、次の WebSocket と RPC メソッドを参考にしています:

<CardGroup cols={2}>
  <Card title="getTransactionsForAddress" href="/ja/rpc/gettransactionsforaddress">
    フィルタリング、ソート、トークンアカウントサポート付きの完全なトランザクション履歴 (Helius専用)
  </Card>

  <Card title="getTransfersByAddress" href="/ja/rpc/gettransfersbyaddress">
    支払いと調整のための解析済みトークンと SOL 転送履歴 (Helius専用)
  </Card>

  <Card title="getTransaction" href="/ja/api-reference/rpc/http/gettransaction">
    シグネチャで完全なトランザクション詳細を取得
  </Card>

  <Card title="getProgramAccounts" href="/ja/api-reference/rpc/http/getprogramaccounts">
    プログラムが所有するすべてのアカウントを取得
  </Card>

  <Card title="getTokenAccountsByOwner" href="/ja/api-reference/rpc/http/gettokenaccountsbyowner">
    ウォレットのトークンアカウントを取得
  </Card>

  <Card title="getMultipleAccountsInfo" href="/ja/api-reference/rpc/http/getmultipleaccounts">
    複数のアカウント詳細をバッチで取得
  </Card>

  <Card title="getAccountInfo" href="/ja/api-reference/rpc/http/getaccountinfo">
    単一のアカウント情報を取得
  </Card>

  <Card title="accountSubscribe" href="/ja/api-reference/rpc/websocket/accountsubscribe">
    WebSocket 経由でアカウントの変更を購読
  </Card>

  <Card title="programSubscribe" href="/ja/api-reference/rpc/websocket/programsubscribe">
    WebSocket 経由でプログラムアカウントの変更を購読
  </Card>

  <Card title="logsSubscribe" href="/ja/api-reference/rpc/websocket/logssubscribe">
    WebSocket 経由でトランザクションログを購読
  </Card>
</CardGroup>

## まとめ

これらの最適化技術を実装することで、以下を達成できます:

* API コールボリュームの**60-90%削減**
* リアルタイムオペレーションの**大幅なレイテンシー削減**
* ターゲットクエリによる**帯域幅使用量の削減**
* スマート再試行ロジックによる**エラー耐性の向上**
* 効率的なリソース使用による**運用コストの削減**

<Card title="次のステップ" icon="arrow-right">
  これらの最適化を実装する準備は整いましたか？トランザクション固有のベストプラクティスについては、[トランザクション最適化ガイド](/ja/sending-transactions/optimizing-transactions) をご覧ください。
</Card>
