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

# Wie man getMultipleAccounts verwendet

> Erfahren Sie mehr über die Anwendungsfälle, Codebeispiele, Anforderungsparameter, Antwortstruktur und Tipps zu getMultipleAccounts.

Die [`getMultipleAccounts`](https://www.helius.dev/docs/api-reference/rpc/http/getmultipleaccounts)-RPC-Methode ist ein hocheffizienter Weg, um Informationen für eine Liste von Solana-Konten gleichzeitig abzurufen. Anstatt individuelle `getAccountInfo`-Anfragen für jedes Konto zu stellen, ermöglicht `getMultipleAccounts` Ihnen, diese Anfragen zu bündeln, was den Netzwerkaufwand reduziert und die Reaktionsfähigkeit Ihrer Anwendung verbessert.

## Häufige Anwendungsfälle

* **Batch-Laden von Kontodaten:** Wenn Ihre Anwendung Daten mehrerer bekannter Konten anzeigen oder verarbeiten muss (z. B. Token-Konten eines Benutzers, eine Liste von On-Chain-Programmkonfigurationen).
* **Portfoliotracker:** Abrufen von Salden und Zuständen für zahlreiche Token-Konten, die einem Benutzer gehören.
* **Marktplatz-Benutzeroberflächen:** Anzeigen von Details mehrerer NFTs oder gelisteter Artikel, indem deren Kontodaten auf einmal abgerufen werden.
* **Verbesserung der dApp-Leistung:** Signifikante Reduzierung der Anzahl von RPC-Anrufen, was zu schnelleren Ladezeiten und einer besseren Benutzererfahrung führt, insbesondere bei der Arbeit mit vielen Konten.

## Anforderungsparameter

1. **`pubkeys`** (`array` von `string`, erforderlich):
   * Ein Array von base-58-codierten öffentlichen Schlüsselzeichenfolgen für die Konten, die Sie abfragen möchten.
   * Maximal 100 öffentliche Schlüssel pro Anfrage.
   * Beispiel: `["So11111111111111111111111111111111111111112", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"]`

2. **`options`** (`object`, optional): Ein Konfigurationsobjekt mit einem oder mehreren der folgenden Felder:
   * **`commitment`** (`string`): Gibt die [Verpflichtungsstufe](https://www.helius.dev/blog/solana-commitment-levels) für die Abfrage an (z. B. `"finalized"`, `"confirmed"`, `"processed"`).
   * **`encoding`** (`string`): Die Codierung für die Kontodaten. Optionen umfassen:
     * `"base64"` (Standard): Normale base64-Codierung.
     * `"base58"`: Langsamer, aber in einigen Kontexten nützlich.
     * `"base64+zstd"`: Base64-codierte zstd-komprimierte Daten.
     * `"jsonParsed"`: Wenn das Konto von einem Programm verwaltet wird, für das der RPC-Knoten einen Parser hat (z. B. SPL Token Program, Stake Program), wird das `data`-Feld ein JSON-Objekt sein. Dies ist sehr nützlich für strukturierte Daten.
   * **`dataSlice`** (`object`): Ermöglicht das Abrufen nur eines bestimmten Teils der Kontodaten. Dies ist nützlich für große Konten, bei denen Sie nur ein kleines Stück Information benötigen.
     * `offset` (`usize`): Der Versatz in Bytes vom Anfang der Kontodaten.
     * `length` (`usize`): Die Anzahl der Bytes, die vom Versatz zurückgegeben werden sollen.
     * *Hinweis: `dataSlice` ist nur verfügbar für `base58`, `base64` oder `base64+zstd`-Codierungen.*
   * **`minContextSlot`** (`u64`): Der minimale Slot, bei dem die Anfrage ausgewertet werden kann.

## Antwortstruktur

Das JSON-RPC-Antwortobjekt enthält ein `result`-Feld mit:

* **`context`** (`object`):
  * `slot` (`u64`): Der Slot, bei dem die Informationen abgerufen wurden.
  * `apiVersion` (`string`, optional): Die API-Version des Knotens.
* **`value`** (`array`):
  * Ein Array, wobei jedes Element dem öffentlichen Schlüssel am gleichen Index im `pubkeys`-Array der Anfrage entspricht.
  * Jedes Element wird entweder sein:
    * `null`: Wenn das Konto mit dem angegebenen öffentlichen Schlüssel nicht existiert oder ein Fehler für dieses spezifische Konto aufgetreten ist.
    * Ein **Kontobjekt** mit den folgenden Feldern:
      * `lamports` (`u64`): Die Anzahl der Lamports, die das Konto besitzt.
      * `owner` (`string`): Der base-58-codierte öffentliche Schlüssel des Programms, dem das Konto gehört.
      * `data` (`array` oder `object`): Die Kontodaten. Wenn `encoding` `jsonParsed` ist und ein Parser existiert, wird dies ein JSON-Objekt sein. Andernfalls ist es in der Regel ein Array `["encoded_string", "encoding_format"]` (z. B. `["SGVsbG8=", "base64"]`).
      * `executable` (`boolean`): Ob das Konto ein Programm enthält (ausführbar ist).
      * `rentEpoch` (`u64`): Die nächste Epoche, in der dieses Konto Miete schuldet.
      * `space` (`u64`): Die Datenlänge des Kontos in Bytes.

## Beispiele

### 1. Grundlegende Informationen für zwei Konten abrufen

Dieses Beispiel ruft Daten für zwei Konten ab: das SOL Llama (ein NFT) und das 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. Analysierte Token-Kontodaten abrufen

Dieses Beispiel ruft Daten für zwei SPL-Token-Konten ab und verlangt `jsonParsed`-Codierung, um strukturierte Daten zu erhalten.

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

## Entwicklertipps

* **Maximal 100 Konten:** Sie können bis zu 100 Konten pro Aufruf anfordern.
* **Atomizität:** Die Anfrage ist nicht atomar; das bedeutet, dass wenn eine Kontosuche fehlschlägt, andere dennoch erfolgreich sein können. Überprüfen Sie jedes Element im `value`-Array auf `null`.
* **`jsonParsed` Bequemlichkeit:** Die Verwendung von `jsonParsed`-Codierung wird dringend empfohlen, wenn Sie mit häufigen Kontotypen wie SPL-Token-Konten arbeiten, da es Ihnen die manuelle Deserialisierung erspart.
* **`dataSlice` für große Konten:** Für sehr große Konten (z. B. einige Programmzustandskonten) verwenden Sie `dataSlice`, um nur die erforderlichen Bytes abzurufen und übermäßigen Datenverkehr zu vermeiden.
* **Fehlerbehandlung:** Seien Sie darauf vorbereitet, `null`-Einträge im `value`-Array der Antwort zu behandeln, was darauf hinweist, dass ein Konto nicht gefunden wurde oder nicht abgerufen werden konnte.

Durch die Nutzung von `getMultipleAccounts` können Sie leistungsfähigere und skalierbarere Solana-Anwendungen entwickeln.

## Verwandte Methoden

<CardGroup cols={2}>
  <Card title="getAccountInfo" href="/docs/de/api-reference/rpc/http/getaccountinfo">
    Abrufen detaillierter Informationen für ein einzelnes Konto
  </Card>

  <Card title="getProgramAccounts" href="/docs/de/api-reference/rpc/http/getprogramaccounts">
    Abrufen aller Konten, die im Besitz eines bestimmten Programms sind
  </Card>
</CardGroup>
