> ## 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钱包的交易历史

> 获取任何Solana钱包的完整交易历史，包括每笔交易的余额变化。适用于投资组合跟踪、会计工具和分析平台。

<Note>
  钱包 API 处于 Beta 阶段。端点和响应格式可能会更改。
</Note>

## 概述

Transaction History 端点使用增强交易 API 检索 Solana 钱包的完整交易历史记录。它返回可读的、解析后的交易及每笔交易的余额变化，以时间倒序（最新的优先）。

该端点每次请求最多返回 100 笔交易，因此分页是手动的。使用 `before` 参数和 `pagination.nextCursor` 以获取下一页，并查看 `pagination.hasMore` 了解是否有更多结果可用。每个请求是一个 API 调用，消耗 100 个积分。

`tokenAccounts` 参数控制是否包括钱包拥有的代币账户的交易：

* `balanceChanged`（推荐）：包括改变代币账户余额的交易，过滤垃圾信息。
* `none`：仅限于直接的账户互动。
* `all`：所有代币账户交易，包括垃圾信息。

<Warning>
  `tokenAccounts` 过滤器依赖于代币余额元数据中的 `owner` 字段，该字段在 slot 111,491,819（\~2022年12月）之前不可用。涉及 slot 之前激活的代币账户的交易可能会丢失。查看 [getTransactionsForAddress 教程](/zh/rpc/gettransactionsforaddress#limitations-and-edge-cases) 以获取解决方法。
</Warning>

## 何时使用

需要使用 Transaction History API 的情况：

* **显示交易动态**：向用户展示完整的交易历史。
* **计算损益**：跟踪所有交易的收益和损失。
* **税务和会计**：生成完整的交易报告以进行报税。
* **投资组合分析**：分析交易模式和活动。
* **审计追踪**：维护完整的钱包活动记录。
* **余额重建**：从历史数据重建当前余额。

## 快速开始

### 基本历史查询

获取最近余额变化的交易：

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={"system"}
    const getTransactionHistory = async (address) => {
      const url = `https://api.helius.xyz/v1/wallet/${address}/history?api-key=YOUR_API_KEY`;

      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      console.log(`Found ${data.data.length} transactions`);

      // Display recent transactions
      data.data.forEach(tx => {
        const date = new Date(tx.timestamp * 1000).toLocaleString();
        const status = tx.error ? 'Failed' : 'Success';

        console.log(`\n${status} - ${date}`);
        console.log(`Signature: ${tx.signature.slice(0, 20)}...`);
        console.log(`Fee: ${tx.fee} SOL`);

        // Show balance changes
        tx.balanceChanges.forEach(change => {
          const sign = change.amount > 0 ? '+' : '';
          console.log(`  ${sign}${change.amount} ${change.mint === 'SOL' ? 'SOL' : change.mint.slice(0, 8)}...`);
        });
      });

      return data;
    };

    getTransactionHistory("86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY");
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"system"}
    import requests
    from datetime import datetime

    def get_transaction_history(address: str):
        url = f"https://api.helius.xyz/v1/wallet/{address}/history"
        headers = {"X-Api-Key": "YOUR_API_KEY"}

        response = requests.get(url, headers=headers)
        response.raise_for_status()

        data = response.json()

        print(f"Found {len(data['data'])} transactions")

        # Display recent transactions
        for tx in data['data']:
            date = datetime.fromtimestamp(tx['timestamp']).strftime('%Y-%m-%d %H:%M:%S')
            status = 'Failed' if tx.get('error') else 'Success'

            print(f"\n{status} - {date}")
            print(f"Signature: {tx['signature'][:20]}...")
            print(f"Fee: {tx['fee']} SOL")

            # Show balance changes
            for change in tx['balanceChanges']:
                sign = '+' if change['amount'] > 0 else ''
                mint_display = 'SOL' if change['mint'] == 'SOL' else change['mint'][:8] + '...'
                print(f"  {sign}{change['amount']} {mint_display}")

        return data

    get_transaction_history("86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY")
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={"system"}
    curl "https://api.helius.xyz/v1/wallet/86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY/history?api-key=YOUR_API_KEY"
    ```
  </Tab>
</Tabs>

### 完整历史的分页

使用参数 `before` 分页获取所有交易：

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={"system"}
    const getAllTransactionHistory = async (address) => {
      let allTransactions = [];
      let before = null;

      do {
        const url = before
          ? `https://api.helius.xyz/v1/wallet/${address}/history?api-key=YOUR_API_KEY&before=${before}`
          : `https://api.helius.xyz/v1/wallet/${address}/history?api-key=YOUR_API_KEY`;

        const response = await fetch(url);
        const data = await response.json();

        allTransactions = allTransactions.concat(data.data);
        before = data.pagination.hasMore ? data.pagination.nextCursor : null;

        console.log(`Fetched ${allTransactions.length} transactions so far...`);

      } while (before);

      console.log(`\nTotal transactions: ${allTransactions.length}`);
      return allTransactions;
    };

    getAllTransactionHistory("86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY");
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"system"}
    def get_all_transaction_history(address: str):
        all_transactions = []
        before = None

        while True:
            url = f"https://api.helius.xyz/v1/wallet/{address}/history"
            params = {"api-key": "YOUR_API_KEY"}

            if before:
                params["before"] = before

            response = requests.get(url, params=params, headers={"X-Api-Key": "YOUR_API_KEY"})
            response.raise_for_status()

            data = response.json()
            all_transactions.extend(data['data'])

            print(f"Fetched {len(all_transactions)} transactions so far...")

            if not data['pagination']['hasMore']:
                break

            before = data['pagination']['nextCursor']

        print(f"\nTotal transactions: {len(all_transactions)}")
        return all_transactions

    get_all_transaction_history("86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY")
    ```
  </Tab>
</Tabs>

## 查询参数

| 参数              | 类型      | 默认值            | 描述                                                 |
| --------------- | ------- | -------------- | -------------------------------------------------- |
| `limit`         | integer | 100            | 每次请求的最大交易数量（1-100）                                 |
| `before`        | string  | -              | 获取此签名之前的交易（使用上一个响应的 `pagination.nextCursor`）       |
| `after`         | string  | -              | 获取此签名之后的交易（用于升序分页）                                 |
| `type`          | string  | -              | 按交易类型过滤（例如，SWAP, TRANSFER, NFT\_SALE, TOKEN\_MINT） |
| `tokenAccounts` | string  | balanceChanged | 过滤涉及代币账户的交易：`none`, `balanceChanged`（推荐），或 `all`   |

### 可用的交易类型

参数 `type` 支持按以下交易类型过滤：

`SWAP`, `TRANSFER`, `NFT_SALE`, `NFT_BID`, `NFT_LISTING`, `NFT_MINT`, `NFT_CANCEL_LISTING`, `TOKEN_MINT`, `BURN`, `COMPRESSED_NFT_MINT`, `COMPRESSED_NFT_TRANSFER`, `COMPRESSED_NFT_BURN`, `CREATE_STORE`, `WHITELIST_CREATOR`, `ADD_TO_WHITELIST`, `REMOVE_FROM_WHITELIST`, `AUCTION_MANAGER_CLAIM_BID`, `EMPTY_PAYMENT_ACCOUNT`, `UPDATE_PRIMARY_SALE_METADATA`, `ADD_TOKEN_TO_VAULT`, `ACTIVATE_VAULT`, `INIT_VAULT`, `INIT_BANK`, `INIT_STAKE`, `MERGE_STAKE`, `SPLIT_STAKE`, `CREATE_AUCTION_MANAGER`, `START_AUCTION`, `CREATE_AUCTION_MANAGER_V2`, `UPDATE_EXTERNAL_PRICE_ACCOUNT`, `EXECUTE_TRANSACTION`

### 过滤示例

<Tabs>
  <Tab title="按类型过滤">
    ```javascript theme={"system"}
    // Get only SWAP transactions
    const url = `https://api.helius.xyz/v1/wallet/${address}/history?api-key=YOUR_API_KEY&type=SWAP`;
    ```
  </Tab>

  <Tab title="代币账户过滤">
    ```javascript theme={"system"}
    // Exclude spam by only including transactions that changed token balances
    const url = `https://api.helius.xyz/v1/wallet/${address}/history?api-key=YOUR_API_KEY&tokenAccounts=balanceChanged`;

    // Only show direct wallet interactions
    const url = `https://api.helius.xyz/v1/wallet/${address}/history?api-key=YOUR_API_KEY&tokenAccounts=none`;
    ```
  </Tab>

  <Tab title="组合筛选器">
    ```javascript theme={"system"}
    // Get only NFT sales that changed balances
    const url = `https://api.helius.xyz/v1/wallet/${address}/history?api-key=YOUR_API_KEY&type=NFT_SALE&tokenAccounts=balanceChanged`;
    ```
  </Tab>
</Tabs>

## 响应格式

```json theme={"system"}
{
  "data": [
    {
      "signature": "5wHu1qwD7Jsj3xqWjdSEJmYr3Q5f5RjXqjqQJ7jqEj7jqEj7jqEj7jqEj7jqEj7jqE",
      "timestamp": 1704067200,
      "slot": 250000000,
      "fee": 0.000005,
      "feePayer": "86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY",
      "error": null,
      "balanceChanges": [
        {
          "mint": "So11111111111111111111111111111111111111111",
          "amount": -0.05,
          "decimals": 9
        },
        {
          "mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
          "amount": 50.0,
          "decimals": 6
        }
      ]
    }
  ],
  "pagination": {
    "hasMore": true,
    "nextCursor": "5wHu1qwD7Jsj3xqWjdSEJmYr3Q5f5RjXqjqQJ7jqEj7jqEj7jqEj7jqEj7jqEj7jqE"
  }
}
```

### 字段说明

* **`timestamp`**: Unix 秒。对于尚未完全处理的最新交易，可能为 `null`。
* **`error`**: 成功交易为 `null`；失败的交易为错误值。失败的交易仍会产生费用。
* **`balanceChanges`**: 钱包在交易中持有量的变化 — 正数 `amount` 表示接收到的代币，负数 `amount` 表示发送或花费的代币。
* **`mint`** (在 `balanceChanges` 内): 代币铸造地址，或本地 SOL 为 `"SOL"`。
* **`amount`** (在 `balanceChanges` 内): **人类可读**，已除以 `decimals` — `-0.05` 表示 −0.05 SOL，而不是 −0.05 lamports。此端点不包括原始 `amountRaw` 字段。

#### 示例余额变化

```javascript theme={"system"}
// Swap: Sold 0.05 SOL, received 5 USDC
{
  "balanceChanges": [
    { "mint": "SOL", "amount": -0.05, "decimals": 9 },
    { "mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "amount": 5.0, "decimals": 6 }
  ]
}

// Simple transfer: Sent 10 USDC
{
  "balanceChanges": [
    { "mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "amount": -10.0, "decimals": 6 }
  ]
}
```

## 用例

### 计算总交易量

汇总所有转账以获得交易量:

```javascript theme={"system"}
const calculateTradingVolume = async (address, tokenMint) => {
  const transactions = await getAllTransactionHistory(address);

  let totalVolume = 0;

  transactions.forEach(tx => {
    tx.balanceChanges.forEach(change => {
      if (change.mint === tokenMint) {
        totalVolume += Math.abs(change.amount);
      }
    });
  });

  console.log(`Total ${tokenMint} volume: ${totalVolume}`);
  return totalVolume;
};

// Example: Calculate total USDC volume
calculateTradingVolume(
  "86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY",
  "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" // USDC
);
```

### 生成税务报告

创建用于报税的交易报告:

```javascript theme={"system"}
const generateTaxReport = async (address, year) => {
  const transactions = await getAllTransactionHistory(address);

  const startDate = new Date(`${year}-01-01`).getTime() / 1000;
  // Set to end of December 31st (23:59:59.999) to include all transactions from that day
  const endDate = new Date(`${year}-12-31T23:59:59.999Z`).getTime() / 1000;

  const taxableTransactions = transactions
    .filter(tx => tx.timestamp >= startDate && tx.timestamp <= endDate)
    .map(tx => ({
      date: new Date(tx.timestamp * 1000).toISOString(),
      signature: tx.signature,
      fee: tx.fee,
      balanceChanges: tx.balanceChanges,
      explorerUrl: `https://orbmarkets.io/tx/${tx.signature}`
    }));

  console.log(`Found ${taxableTransactions.length} transactions in ${year}`);

  // Export as JSON
  const report = {
    address,
    year,
    transactionCount: taxableTransactions.length,
    transactions: taxableTransactions
  };

  console.log(JSON.stringify(report, null, 2));
  return report;
};

generateTaxReport("86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY", 2024);
```

### 跟踪失败的交易

查找所有失败的交易以了解错误:

```javascript theme={"system"}
const getFailedTransactions = async (address) => {
  const data = await getTransactionHistory(address);

  const failed = data.data.filter(tx => tx.error !== null);

  console.log(`Found ${failed.length} failed transactions`);

  failed.forEach(tx => {
    const date = new Date(tx.timestamp * 1000).toLocaleString();
    console.log(`\n${date}`);
    console.log(`Signature: ${tx.signature}`);
    console.log(`Error: ${tx.error}`);
    console.log(`Fee Paid: ${tx.fee} SOL`);
  });

  return failed;
};
```

### 重建历史余额

计算特定时间点的余额:

```javascript theme={"system"}
const getHistoricalBalance = async (address, targetTimestamp) => {
  const transactions = await getAllTransactionHistory(address);

  // Filter to transactions before target date
  const relevantTxs = transactions.filter(tx => tx.timestamp <= targetTimestamp);

  // Sum all balance changes
  const balances = {};

  relevantTxs.forEach(tx => {
    tx.balanceChanges.forEach(change => {
      if (!balances[change.mint]) {
        balances[change.mint] = 0;
      }
      balances[change.mint] += change.amount;
    });
  });

  console.log(`Historical balances as of ${new Date(targetTimestamp * 1000).toLocaleString()}:`);
  Object.entries(balances).forEach(([mint, balance]) => {
    console.log(`${mint}: ${balance}`);
  });

  return balances;
};

// Example: Get balances on Jan 1, 2024
getHistoricalBalance(
  "86xCnPeV69n6t3DnyGvkKobf9FdN2H9oiVDdaMpo2MMY",
  new Date("2024-01-01").getTime() / 1000
);
```

对于单个代币在特定时间点的确切余额，[历史余额](/zh/wallet-api/balance-at) 端点直接从链上后余额读取，而不是在客户端累加变化。

### 分析交易费用

计算支付的总费用:

```javascript theme={"system"}
const analyzeFees = async (address) => {
  const transactions = await getAllTransactionHistory(address);

  const totalFees = transactions.reduce((sum, tx) => sum + tx.fee, 0);
  const avgFee = totalFees / transactions.length;

  const successfulTxs = transactions.filter(tx => !tx.error);
  const failedTxs = transactions.filter(tx => tx.error);

  const wastedFees = failedTxs.reduce((sum, tx) => sum + tx.fee, 0);

  console.log(`Total Transactions: ${transactions.length}`);
  console.log(`Successful: ${successfulTxs.length}`);
  console.log(`Failed: ${failedTxs.length}`);
  console.log(`Total Fees Paid: ${totalFees.toFixed(6)} SOL`);
  console.log(`Average Fee: ${avgFee.toFixed(6)} SOL`);
  console.log(`Wasted on Failed Txs: ${wastedFees.toFixed(6)} SOL`);

  return {
    totalFees,
    avgFee,
    wastedFees,
    successRate: (successfulTxs.length / transactions.length) * 100
  };
};
```

## 最佳实践

* **使用分页获取完整历史记录。** 有些钱包有成千上万的交易；在获取所有交易时，请始终分页。
* **缓存历史数据。** 历史交易不会更改。将它们缓存在本地，仅获取新的交易。
* **处理失败的交易。** 检查 `error` 字段以区分成功和失败的交易。失败的交易仍会产生费用。
* **使用时间戳进行日期过滤。** 时间戳是 Unix 秒。转换为本地日期进行显示和过滤。

## 常见错误

| 错误代码 | 描述            | 解决方案                      |
| ---- | ------------- | ------------------------- |
| 400  | 无效的钱包地址格式     | 验证地址是有效的 base58 Solana 地址 |
| 401  | 缺少或无效的 API 密钥 | 确保请求中包含 API 密钥            |
| 429  | 超过速率限制        | 减少请求频率或升级你的计划             |

## 后续步骤

<CardGroup cols={3}>
  <Card title="Token Transfers" icon="arrow-right-arrow-left" href="/zh/wallet-api/transfers">
    仅限转账视图，包含发送者/接收者信息，比完整历史简单。
  </Card>

  <Card title="Wallet API Overview" icon="wallet" href="/zh/wallet-api/overview">
    所有 Wallet API 端点和共享约定。
  </Card>

  <Card title="API Reference" icon="code" href="/zh/api-reference/wallet-api/history">
    交易历史的请求和响应模式。
  </Card>
</CardGroup>
