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

# Leer el historial privado

> Guía para leer el historial de transacciones privadas de una cartera desde el indexador, con un ejemplo de código completo.

1. La lectura obtiene las transacciones cifradas del indexador mediante métodos RPC específicos.
2. Solo el usuario, o cualquier persona que este autorice, puede descifrar el historial con su clave de visualización.
3. Úsala siempre que la cartera ejecute recuperaciones de datos históricos: al desbloquear la cartera, abrir la cartera privada, reanudar la aplicación, volver a conectarse a la red, detectar una interrupción en el flujo o restaurar la cartera.

```mermaid theme={"system"}
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'lineColor':           '#FF6B35',
    'primaryTextColor':    '#737373',
    'primaryBorderColor':  '#9CA3AF',
    'actorBkg':            '#FFFFFF',
    'actorBorder':         '#9CA3AF',
    'actorTextColor':      '#737373',
    'signalColor':         '#FF6B35',
    'signalTextColor':     '#737373',
    'labelBoxBkgColor':    '#FF6B351F',
    'labelBoxBorderColor': '#FF6B35',
    'noteBkgColor':        '#F5F5F5',
    'noteTextColor':       '#737373',
    'noteBorderColor':     '#9CA3AF'
  }
}}%%
sequenceDiagram
    participant Wallet
    participant RPC as RPC Provider

    Wallet->>RPC: getShieldedTransactionsByTags
    RPC-->>Wallet: Encrypted transactions
    Note over Wallet: Decrypt
    Note over Wallet: Decrypt to private history
```

<Accordion title="Compare to getSignaturesForAddress">
  1. `getSignaturesForAddress` devuelve firmas públicas.
  2. El RPC devuelve el historial público.

  ```mermaid theme={"system"}
  %%{init: {
    'theme': 'base',
    'themeVariables': {
      'lineColor':           '#FF6B35',
      'primaryTextColor':    '#737373',
      'primaryBorderColor':  '#9CA3AF',
      'actorBkg':            '#FFFFFF',
      'actorBorder':         '#9CA3AF',
      'actorTextColor':      '#737373',
      'signalColor':         '#FF6B35',
      'signalTextColor':     '#737373',
      'labelBoxBkgColor':    '#FF6B351F',
      'labelBoxBorderColor': '#FF6B35',
      'noteBkgColor':        '#F5F5F5',
      'noteTextColor':       '#737373',
      'noteBorderColor':     '#9CA3AF'
    }
  }}%%
  sequenceDiagram
      participant Wallet
      participant RPC

      Wallet->>RPC: getSignaturesForAddress
      RPC-->>Wallet: Public signatures
  ```
</Accordion>

## Comenzar

<Tabs>
  <Tab title="TypeScript Client">
    <Steps>
      <Step>
        ### Requisitos previos

        <Info>
          The TypeScript examples require Node.js 24 or later, pnpm 11.18.0, and the Solana CLI.
        </Info>

        ```bash theme={"system"}
        pnpm add @heliuslabs/zolana@0.2.0-alpha @solana/kit@^8.3.0
        ```

        Source: [sdk-libs/ts](https://github.com/helius-labs/zolana/tree/ebca3ad1bd2f27b1f1f04e33fbfa3cc4c7bbf856/sdk-libs/ts)

        <Accordion title="Connect to Endpoints">
          <Tabs>
            <Tab title="Devnet">
              ```bash theme={"system"}
              pnpm install
              cp .env.example .env
              ```

              Add a [Helius API key](https://dashboard.helius.dev/):

              ```bash .env theme={"system"}
              API_KEY=YOUR_API_KEY
              ZOLANA_PAYER_KEYPAIR=~/.config/solana/id.json
              ```

              ```ts theme={"system"}
              import { createZolanaClient } from "@heliuslabs/zolana";

              const client = await createZolanaClient({
                solanaRpcUrl: "https://devnet.helius-rpc.com/?api-key=YOUR_API_KEY",
                indexerUrl: "https://d2xah7tnhdhcom.cloudfront.net",
                proverUrl: "https://d21ni15goiip6l.cloudfront.net",
              });
              ```

              The examples use the Solana CLI wallet as the payer by default. The payer must hold devnet SOL. See [How to Get Devnet SOL](/docs/rpc/devnet-sol).
            </Tab>

            <Tab title="Localnet">
              On localnet the SDK starts the local test validator (`:8899`), Photon indexer (`:8784`), and prover (`:3001`), and the
              client connects to them automatically without needing endpoint configuration.

              ```bash theme={"system"}
              cargo install --git https://github.com/helius-labs/zolana --tag v0.1.0-alpha zolana-cli
              zolana dev start
              ```

              ```ts theme={"system"}
              import { createZolanaClient } from "@heliuslabs/zolana";

              const client = await createZolanaClient({});
              ```
            </Tab>
          </Tabs>
        </Accordion>
      </Step>

      <Step>
        ### Derivar la etiqueta de visualización

        ```typescript theme={"system"}
        import { createZolanaClient } from "@heliuslabs/zolana";

        // The view tag is the sender's Solana public key in confidential rings.
        // Used by the indexer to fetch the sender's UTXOs.
        const senderViewTag =
          senderAddress.confidentialViewTag();
        ```

        * `senderViewTag` es `senderAddress.confidentialViewTag()`, la clave pública de Solana del remitente en anillos confidenciales. El indexador la usa para devolver las salidas cifradas coincidentes.
      </Step>

      <Step>
        ### Obtener las salidas de transacciones del indexador

        ```typescript theme={"system"}
        import { atSlot } from "@heliuslabs/zolana/client";

        const depositResponse =
          await client.getShieldedTransactionsByTags(
            { tags: [senderViewTag] },
            atSlot(depositTx.slot),
          );
        ```

        * `getShieldedTransactionsByTags` obtiene las salidas cifradas asociadas con `senderViewTag`.
        * `atSlot(depositTx.slot)` espera hasta que el indexador tenga el depósito en ese slot.
        * El indexador devuelve datos de salida cifrados. No descifra el historial privado.
      </Step>

      <Step>
        ### Descifrar para obtener el historial privado

        ```typescript theme={"system"}
        import { Wallet } from "@heliuslabs/zolana";
        import { decryptTransactions, LocalShieldedKeys } from "@heliuslabs/zolana/transaction";

        const wallet = new Wallet({
          identity: senderAddress,
          registry: assets,
        });
        await decryptTransactions({
          wallet,
          keys: LocalShieldedKeys.fromKeypair(sender),
          transactions: depositResponse.transactions,
        });
        const history = wallet.privateTransactions();
        ```

        * `LocalShieldedKeys.fromKeypair(sender)` proporciona las claves del remitente para el descifrado local.
        * `decryptTransactions` descifra las salidas coincidentes y escribe el historial en `Wallet`.
        * `wallet.privateTransactions()` lee el historial descifrado.
        * `decryptToBalances` solo devuelve saldos.

        **Respuesta de ejemplo:**

        ```ts theme={"system"}
        [
          {
            id: { signature: "5x…", slot: 291044100n, index: 0n },
            kind: "deposit",
            direction: "inbound",
            status: "confirmed",
            asset: SOL_MINT,
            amount: 100_000_000n,
            counterpartyViewingPublicKey: undefined,
          },
        ]
        ```

        <Note>
          Consulta [Conceptos](/docs/es/privacy/concepts) para saber cómo funcionan el etiquetado de propietarios y las cuentas privadas de tokens de Solana.
        </Note>
      </Step>
    </Steps>

    ### Ejemplo de código completo

    Clona y ejecuta el ejemplo:

    ```bash theme={"system"}
    git clone https://github.com/helius-labs/zolana-examples.git
    cd zolana-examples/typescript-client
    pnpm install
    pnpm example examples/read_history.ts
    ```

    <Info>
      Los ejemplos usan un anillo confidencial en local/devnet [aquí](https://github.com/helius-labs/zolana-examples/blob/7775438e0a290a4c28dccf919719bd640c3ec5e3/typescript-client/examples/read_history.ts).
    </Info>
  </Tab>

  <Tab title="Rust Client">
    <Steps>
      <Step>
        ### Requisitos previos

        <Info>
          The Rust examples require Rust 1.98.1 and the Solana CLI v4.0.2. See the [Solana installation guide](https://solana.com/docs/intro/installation).
        </Info>

        ```toml Cargo.toml theme={"system"}
        [dependencies]
        zolana-client = { git = "https://github.com/helius-labs/zolana", tag = "v0.2.0-alpha", features = ["indexer-api", "solana-rpc"] }
        zolana-interface = { git = "https://github.com/helius-labs/zolana", tag = "v0.2.0-alpha", features = ["solana"] }
        zolana-keypair = { git = "https://github.com/helius-labs/zolana", tag = "v0.2.0-alpha" }
        zolana-transaction = { git = "https://github.com/helius-labs/zolana", tag = "v0.2.0-alpha" }
        zolana-wallet = { git = "https://github.com/helius-labs/zolana", tag = "v0.2.0-alpha" }
        ```

        Source: [sdk-libs/client](https://github.com/helius-labs/zolana/tree/v0.2.0-alpha/sdk-libs/client)

        <Accordion title="Connect to Endpoints">
          <Tabs>
            <Tab title="Devnet">
              Add a [Helius API key](https://dashboard.helius.dev/):

              ```bash .env theme={"system"}
              API_KEY=YOUR_API_KEY
              ZOLANA_PAYER_KEYPAIR=~/.config/solana/id.json
              ```

              ```rust theme={"system"}
              use zolana_client::{SolanaRpc, ZolanaClient};
              use zolana_interface::pda;

              let tree = pda::tree(0);
              let client = ZolanaClient::from_urls(
                  SolanaRpc::new("https://devnet.helius-rpc.com/?api-key=YOUR_API_KEY"),
                  "https://d2xah7tnhdhcom.cloudfront.net",
                  "https://d21ni15goiip6l.cloudfront.net",
                  tree,
              )?;
              ```

              The examples use the Solana CLI wallet as the payer by default. The payer must hold devnet SOL. See [How to Get Devnet SOL](/docs/rpc/devnet-sol).
            </Tab>

            <Tab title="Localnet">
              ```bash theme={"system"}
              cargo install --git https://github.com/helius-labs/zolana --tag v0.1.0-alpha zolana-cli
              zolana dev start
              ```

              ```rust theme={"system"}
              use zolana_client::{SolanaRpc, ZolanaClient};
              use zolana_interface::pda;

              let tree = pda::tree(0);
              let client = ZolanaClient::from_urls(
                  SolanaRpc::new("http://127.0.0.1:8899"),
                  "http://127.0.0.1:8784",
                  "http://127.0.0.1:3001",
                  tree,
              )?;
              ```
            </Tab>
          </Tabs>
        </Accordion>
      </Step>

      <Step>
        ### Derivar la etiqueta de visualización

        ```rust theme={"system"}
        use zolana_client::Rpc;

        let sender_tag = sender_shielded_address.confidential_view_tag()?;
        ```

        * `sender_tag` es `sender_shielded_address.confidential_view_tag()`, la clave pública de Solana del remitente en anillos confidenciales. El indexador la usa para devolver las salidas cifradas coincidentes.
      </Step>

      <Step>
        ### Obtener las salidas de transacciones del indexador

        ```rust theme={"system"}
        use zolana_client::{IndexerRpcConfig, Rpc};

        let response = client.get_shielded_transactions_by_tags(
            vec![sender_tag],
            None,
            Some(50),
            Some(IndexerRpcConfig::at_slot(slot)),
        )?;
        ```

        * `get_shielded_transactions_by_tags` obtiene las salidas cifradas asociadas con `sender_tag`.
        * `IndexerRpcConfig::at_slot(slot)` espera hasta que el indexador tenga el depósito en ese slot.
        * El indexador devuelve datos de salida cifrados. No descifra el historial privado.
      </Step>

      <Step>
        ### Descifrar para obtener el historial privado

        ```rust theme={"system"}
        use anyhow::anyhow;
        use zolana_transaction::{Wallet, DEFAULT_TAG_WINDOW};

        let mut wallet = Wallet::new(sender.shielded_address()?, assets.clone())
            .map_err(|e| anyhow!("create wallet: {e:?}"))?;
        wallet
            .sync(&sender, &response.transactions, 0, DEFAULT_TAG_WINDOW)
            .map_err(|e| anyhow!("decrypt sender transactions: {e:?}"))?;
        let history = wallet.private_transactions();
        ```

        * `sender` proporciona la clave de visualización del remitente para el descifrado local.
        * `Wallet::sync` descifra las salidas coincidentes y escribe el historial en `Wallet`.
        * `wallet.private_transactions()` lee el historial descifrado.
        * `decrypt_transactions` solo devuelve saldos.

        **Respuesta de ejemplo:**

        ```rust theme={"system"}
        [
            PrivateTransaction {
                id: PrivateTransactionId {
                    signature: "5x…".into(),
                    slot: 291044100,
                    index: 0,
                },
                kind: PrivateTransactionKind::Deposit,
                direction: PrivateTransactionDirection::Inbound,
                status: PrivateTransactionStatus::Confirmed,
                asset: SOL_MINT,
                amount: 100_000_000,
                counterparty_viewing_pubkey: None,
            },
        ]
        ```
      </Step>
    </Steps>

    ### Ejemplo de código completo

    Clona y ejecuta el ejemplo:

    ```bash theme={"system"}
    git clone https://github.com/helius-labs/zolana-examples.git
    cd zolana-examples/rust-client
    cargo run -p rust-client-example --example read_history
    ```

    <Info>
      Los ejemplos usan un anillo confidencial en local/devnet [aquí](https://github.com/helius-labs/zolana-examples/blob/7775438e0a290a4c28dccf919719bd640c3ec5e3/rust-client/examples/read_history.rs).
    </Info>
  </Tab>
</Tabs>

## Guías relacionadas

<CardGroup cols={2}>
  <Card title="Read a Private Balance" icon="wallet" href="/docs/es/privacy/guides/read-balance" horizontal />

  <Card title="Deposit" icon="arrow-down-to-bracket" href="/docs/es/privacy/guides/deposit" horizontal />

  <Card title="Transfer" icon="arrow-right-arrow-left" href="/docs/es/privacy/guides/transfer" horizontal />

  <Card title="Withdraw" icon="arrow-up-from-bracket" href="/docs/es/privacy/guides/withdraw" horizontal />
</CardGroup>

## Didn't find what you were looking for?

<Callout type="info">
  Reach out! [Telegram](https://t.me/tilo_light) | [E-Mail](mailto:sales@helius.xyz) | [Contact](https://www.helius.dev/contact)
</Callout>
