> ## 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.

# getMultipleAccountsの使用方法

> getMultipleAccountsの使用例、コード例、リクエストパラメータ、応答構造、およびヒントを学びます。

[`getMultipleAccounts`](https://www.helius.dev/docs/api-reference/rpc/http/getmultipleaccounts) RPC メソッドは、Solana アカウントのリストに対する情報を同時に取得するための非常に効率的な方法です。各アカウントに個別の`getAccountInfo`リクエストを行う代わりに、`getMultipleAccounts`を使用すると、これらのリクエストをバッチ処理でき、ネットワークのオーバーヘッドを削減し、アプリケーションの応答性を向上させます。

## 一般的な使用事例

* **バッチ処理によるアカウントデータの読み込み:** アプリケーションが複数の既知のアカウント（例: ユーザーのトークンアカウント、オンチェーンのプログラム設定のリストからのデータを表示または処理する必要がある場合）。
* **ポートフォリオトラッカー:** ユーザーが所有する多数のトークンアカウントの残高や状態を取得します。
* **マーケットプレイスUI:** 複数のNFTまたは一覧アイテムの詳細を一度に取得して表示します。
* **dAppのパフォーマンス向上:** RPCコールの数を大幅に削減し、多くのアカウントを扱う際の読み込み時間を短縮し、より良いユーザーエクスペリエンスを提供します。

## リクエストパラメータ

1. **`pubkeys`** (`array` of `string`, required):
   * クエリしたいアカウントのBase-58でエンコードされた公開鍵文字列の配列。
   * 1リクエストあたり最大100個の公開鍵。
   * 例: `["So11111111111111111111111111111111111111112", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"]`

2. **`options`** (`object`, optional): 次のいずれかのフィールドを含む構成オブジェクト:
   * **`commitment`** (`string`): クエリに対する[コミットメントレベル](https://www.helius.dev/blog/solana-commitment-levels)を指定します（例: `"finalized"`, `"confirmed"`, `"processed"`）。
   * **`encoding`** (`string`): アカウントデータのエンコーディング。オプションには以下が含まれます:
     * `"base64"` (デフォルト): 標準のbase64エンコーディング。
     * `"base58"`: 遅いが、特定のコンテキストで役立つ場合があります。
     * `"base64+zstd"`: base64でエンコードされたzstd圧縮データ。
     * `"jsonParsed"`: アカウントがRPCノードにパーサーを持つプログラムによって所有されている場合（例: SPLトークンプログラム、ステークプログラム）、`data`フィールドはJSONオブジェクトになります。これは構造化データに非常に役立ちます。
   * **`dataSlice`** (`object`): アカウントデータの特定の部分のみを取得できます。これは、大規模なアカウントで特定の情報のみが必要な場合に役立ちます。
     * `offset` (`usize`): アカウントデータの先頭からのバイトオフセット。
     * `length` (`usize`): オフセットから返すバイト数。
     * *注: `dataSlice`は、`base58`, `base64`, または`base64+zstd`エンコーディングにのみ利用可能です。*
   * **`minContextSlot`** (`u64`): リクエストが評価される際の最低スロット。

## 応答構造

JSON-RPC応答オブジェクトには、以下を含む`result`フィールドがあります:

* **`context`** (`object`):
  * `slot` (`u64`): 情報が取得されたスロット。
  * `apiVersion` (`string`, optional): ノードのAPIバージョン。
* **`value`** (`array`):
  * 配列の各要素は、リクエストの`pubkeys`配列内の同じインデックスの公開鍵に対応します。
  * 各要素は以下のいずれかです:
    * `null`: 指定された公開鍵のアカウントが存在しない場合、またはその特定のアカウントにエラーが発生した場合。
    * **アカウントオブジェクト**次のフィールドを持ちます:
      * `lamports` (`u64`): アカウントが所有するlamportの数。
      * `owner` (`string`): アカウントを所有するプログラムのBase-58でエンコードされた公開鍵。
      * `data` (`array` または `object`): アカウントデータ。`encoding`が`jsonParsed`であり、パーサーが存在する場合、これはJSON オブジェクトになります。それ以外の場合、通常は配列`["encoded_string", "encoding_format"]`（例: `["SGVsbG8=", "base64"]`）。
      * `executable` (`boolean`): アカウントにプログラムが含まれているかどうか（実行可能か）。
      * `rentEpoch` (`u64`): このアカウントが次のエポックで家賃を支払う必要があるスロット。
      * `space` (`u64`): アカウントのデータ長（バイト単位）。

## 例

### 1. 2つのアカウントの基本情報を取得

この例は、SOL Llama（NFT）とSerum Dex Program v3のデータを取得します。

<CodeGroup>
  ```bash cURL theme={"system"}
  # Replace <api-key> with your Helius API key
  # SOL Llama Mint: Abug4qgG1x23AEdjS2h9CEJ1m6ha2Z22LdK2kL2pys3F
  # Serum Dex Program v3: 9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getMultipleAccounts",
      "params": [
        [
          "Abug4qgG1x23AEdjS2h9CEJ1m6ha2Z22LdK2kL2pys3F",
          "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"
        ]
      ]
    }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  // Replace <api-key> with your Helius API key
  const { Connection, PublicKey } = require('@solana/web3.js');

  async function fetchMultipleAccountInfo() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    const accountPubkeys = [
      new PublicKey('Abug4qgG1x23AEdjS2h9CEJ1m6ha2Z22LdK2kL2pys3F'), // SOL Llama
      new PublicKey('9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin')  // Serum Dex Program v3
    ];

    try {
      const accountsInfo = await connection.getMultipleAccountsInfo(accountPubkeys);
      
      accountsInfo.forEach((account, index) => {
        console.log(`--- Account ${index + 1} (${accountPubkeys[index].toBase58()}) ---`);
        if (account) {
          console.log(`  Owner: ${account.owner.toBase58()}`);
          console.log(`  Lamports: ${account.lamports}`);
          console.log(`  Executable: ${account.executable}`);
          console.log(`  Data length: ${account.data.length}`);
          // For brevity, not logging full data buffer
        } else {
          console.log("  Account not found or error fetching.");
        }
      });
    } catch (error) {
      console.error('Error fetching multiple accounts:', error);
    }
  }

  fetchMultipleAccountInfo();
  ```
</CodeGroup>

### 2. 解析されたトークンアカウントデータを取得

この例では、2つのSPLトークンアカウントのデータを取得し、構造化データを取得するために`jsonParsed`エンコーディングを要求します。

<CodeGroup>
  ```bash cURL theme={"system"}
  # Replace <api-key> with your Helius API key
  # Example USDC Token Account 1: GqoZ2MCrdTtygoX1F2b8X7F2tDXxNxyvMvykR9RzQW8p
  # Example USDT Token Account 2: HYnLMbkaPMh9W2aPNy2yP4LzLSWWw9zSCYEZdX2g2E7m
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getMultipleAccounts",
      "params": [
        [
          "GqoZ2MCrdTtygoX1F2b8X7F2tDXxNxyvMvykR9RzQW8p",
          "HYnLMbkaPMh9W2aPNy2yP4LzLSWWw9zSCYEZdX2g2E7m"
        ],
        {
          "encoding": "jsonParsed"
        }
      ]
    }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  // Replace <api-key> with your Helius API key
  const { Connection, PublicKey } = require('@solana/web3.js');

  async function fetchParsedTokenAccounts() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    const tokenAccountPubkeys = [
      new PublicKey('GqoZ2MCrdTtygoX1F2b8X7F2tDXxNxyvMvykR9RzQW8p'), // Example USDC account
      new PublicKey('HYnLMbkaPMh9W2aPNy2yP4LzLSWWw9zSCYEZdX2g2E7m')  // Example USDT account
    ];

    try {
      const accountsInfo = await connection.getMultipleAccountsInfo(tokenAccountPubkeys, 'confirmed'); // Can also pass commitment here
      // Note: @solana/web3.js's getMultipleAccountsInfo automatically requests jsonParsed if the node supports it for token accounts.
      // For explicit control with raw RPC, you use the options object as in the cURL example.

      accountsInfo.forEach((account, index) => {
        console.log(`--- Token Account ${index + 1} (${tokenAccountPubkeys[index].toBase58()}) ---`);
        if (account && account.data && typeof account.data !== 'string') { // Check if data is parsed
          // The actual structure of account.data depends on the program (e.g., SPL Token)
          // For SPL Token accounts, you'd typically find parsed data in account.data.parsed.info
          const parsedInfo = (account.data as any).parsed?.info;
          if (parsedInfo) {
              console.log(`  Mint: ${parsedInfo.mint}`);
              console.log(`  Owner: ${parsedInfo.owner}`);
              console.log(`  Amount: ${parsedInfo.tokenAmount.uiAmountString} (decimals: ${parsedInfo.tokenAmount.decimals})`);
          } else {
              console.log("  Account data is not in the expected parsed format or is not a token account.");
              // console.log("Raw data:", account.data.toString('base64')); // if buffer
          }
        } else if (account) {
          console.log("  Account found, but data is not parsed or is a string (binary data).");
          // console.log("  Raw data:", account.data.toString()); // if string
        } else {
          console.log("  Account not found or error fetching.");
        }
      });
    } catch (error) {
      console.error('Error fetching parsed token accounts:', error);
    }
  }

  fetchParsedTokenAccounts();
  ```
</CodeGroup>

## 開発者向けヒント

* **最大100アカウント:** 1回の呼び出しで最大100アカウントを要求できます。
* **原子性:** リクエストは原子性を持たず、あるアカウントの検索が失敗しても他のアカウントは成功する可能性があります。`value`配列の各要素で`null`を確認してください。
* **`jsonParsed`の便利さ:** SPLトークンアカウントのような一般的なアカウントタイプを扱う場合、手動のデシリアライズを避けるために`jsonParsed`エンコーディングを使用することを強くお勧めします。
* **大型アカウントのための`dataSlice`:** 非常に大きなアカウント（例: 一部のプログラム状態アカウント）には、必要なバイトのみを取得して過剰なデータ転送を避けるために`dataSlice`を使用してください。
* **エラーハンドリング:** アカウントが見つからなかったり取得できなかった場合を示す`null`エントリを応答の`value`配列で処理できるように準備してください。

`getMultipleAccounts`を活用することで、よりパフォーマンスが高くスケーラブルなSolanaアプリケーションを構築できます。

## 関連メソッド

<CardGroup cols={2}>
  <Card title="getAccountInfo" href="/ja/api-reference/rpc/http/getaccountinfo">
    単一のアカウントの詳細情報を取得する
  </Card>

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