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

# 读取私密历史记录

> 从索引器读取钱包私密交易历史的指南，包括完整代码示例。

1. 使用专用的 RPC 方法从索引器读取加密交易。
2. 只有用户或用户授权的人才能使用他们的查看密钥解密历史记录。
3. 在钱包运行回填时使用：在钱包解锁、私密钱包打开、应用恢复、网络重新连接、流间隙或钱包恢复时。

```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="与 getSignaturesForAddress 的比较">
  1. `getSignaturesForAddress` 返回公共签名。
  2. RPC 返回公共历史。

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

# 开始使用

<Tabs>
  <Tab title="TypeScript 客户端">
    <Steps>
      <Step>
        ### 前提条件

        <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 @solana/kit
        ```

        Source: [sdk-libs/ts](https://github.com/helius-labs/zolana/tree/main/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: "http://zolnet-devnet-1779374825.eu-north-1.elb.amazonaws.com",
                proverUrl: "http://zolnet-devnet-1779374825.eu-north-1.elb.amazonaws.com:3001",
                allowInsecureHttp: true,
              });
              ```

              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>
        ### 派生查看标签

        ```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` 是 `senderAddress.confidentialViewTag()`，发送者在机密环中的 Solana 公钥。索引器使用它返回匹配的加密输出。
      </Step>

      <Step>
        ### 从索引器获取交易输出

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

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

        * `getShieldedTransactionsByTags` 获取与 `senderViewTag` 关联的加密输出。
        * `atSlot(depositTx.slot)` 等待索引器在该槽位有存款。
        * 索引器返回加密输出数据。它不解密私密历史。
      </Step>

      <Step>
        ### 解密为私密历史

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

        const wallet = new Wallet({
          identity: senderAddress,
          registry: assets,
        });
        await decryptTransactions({
          wallet,
          authority: {
            syncMaterial: () =>
              Promise.resolve({
                identity: senderAddress,
                viewingKeys: [senderKeypair.viewingKey()],
                nullifierKey: senderKeypair.nullifierKey(),
              }),
          },
          transactions: depositResponse.transactions,
        });
        const history = wallet.privateTransactions();
        ```

        * `senderKeypair` 提供发送者的查看密钥以进行本地解密。
        * `decryptTransactions` 解密匹配输出并将历史记录写入 `Wallet`。
        * `wallet.privateTransactions()` 阅读解密后的历史。
        * `decryptToBalances` 仅返回余额。

        **示例响应：**

        ```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>
          查看[概念](/docs/zh/privacy/concepts)以了解所有者标记和私密 Solana 代币账户的工作方式。
        </Note>
      </Step>
    </Steps>

    ### 完整代码示例

    克隆并运行示例：

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

    <Info>
      这些示例使用本地/devnet 上的机密环 [此处](https://github.com/helius-labs/zolana-examples/blob/main/typescript-client/examples/deposit_transfer_withdraw.ts)。
    </Info>
  </Tab>

  <Tab title="Rust 客户端">
    <Steps>
      <Step>
        ### 前提条件

        <Info>
          The Rust examples require the latest stable Rust toolchain 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.1.0-alpha", features = ["indexer-api", "solana-rpc"] }
        zolana-interface = { git = "https://github.com/helius-labs/zolana", tag = "v0.1.0-alpha", features = ["solana"] }
        zolana-keypair = { git = "https://github.com/helius-labs/zolana", tag = "v0.1.0-alpha" }
        zolana-transaction = { git = "https://github.com/helius-labs/zolana", tag = "v0.1.0-alpha" }
        ```

        Source: [sdk-libs/client](https://github.com/helius-labs/zolana/tree/v0.1.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 solana_address::Address;
              use zolana_client::{SolanaRpc, ZolanaClient};
              use zolana_interface::DEFAULT_TREE_ADDRESS;

              let tree: Address = DEFAULT_TREE_ADDRESS.parse()?;
              let client = ZolanaClient::from_urls_allowing_insecure_http(
                  SolanaRpc::new("https://devnet.helius-rpc.com/?api-key=YOUR_API_KEY"),
                  "http://zolnet-devnet-1779374825.eu-north-1.elb.amazonaws.com",
                  "http://zolnet-devnet-1779374825.eu-north-1.elb.amazonaws.com:3001",
                  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 solana_address::Address;
              use zolana_client::{SolanaRpc, ZolanaClient};
              use zolana_interface::DEFAULT_TREE_ADDRESS;

              let tree: Address = DEFAULT_TREE_ADDRESS.parse()?;
              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>
        ### 派生查看标签

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

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

        * `sender_tag` 是 `sender_shielded_address.confidential_view_tag()`，发送者在机密环中的 Solana 公钥。索引器使用它返回匹配的加密输出。
      </Step>

      <Step>
        ### 从索引器获取交易输出

        ```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` 获取与 `sender_tag` 关联的加密输出。
        * `IndexerRpcConfig::at_slot(slot)` 等待索引器在该槽位有存款。
        * 索引器返回加密输出数据。它不解密私密历史。
      </Step>

      <Step>
        ### 解密为私密历史

        ```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` 提供发送者的查看密钥以进行本地解密。
        * `Wallet::sync` 解密匹配输出并将历史记录写入 `Wallet`。
        * `wallet.private_transactions()` 阅读解密后的历史。
        * `decrypt_transactions` 仅返回余额。

        **示例响应：**

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

    ## 完整代码示例

    克隆并运行示例：

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

    <Info>
      这些示例使用本地/devnet 上的机密环 [此处](https://github.com/helius-labs/zolana-examples/blob/main/rust-client/examples/deposit_transfer_withdraw.rs)。
    </Info>
  </Tab>
</Tabs>

## 相关指南

<CardGroup cols={2}>
  <Card title="读取私密余额" icon="wallet" href="/docs/zh/privacy/guides/read-balance" horizontal />

  <Card title="存款" icon="arrow-down-to-bracket" href="/docs/zh/privacy/guides/deposit" horizontal />

  <Card title="转账" icon="arrow-right-arrow-left" href="/docs/zh/privacy/guides/transfer" horizontal />

  <Card title="取款" icon="arrow-up-from-bracket" href="/docs/zh/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>
