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

# getRecentPrioritizationFeesの使い方

> getRecentPrioritizationFees のユースケース、コード例、リクエストパラメーター、レスポンス構造、ヒントについて学びます。

[`getRecentPrioritizationFees`](https://www.helius.dev/docs/api-reference/rpc/http/getrecentprioritizationfees) RPC メソッドは、Solana ネットワーク上の最近のブロックで支払われた優先手数料についての情報を提供します。これらの手数料を検討することで、開発者はトランザクションに追加する優先手数料 ([priority fee](https://www.helius.dev/blog/priority-fees-understanding-solanas-transaction-fee-mechanics)) についてより良い意思決定を行えます。特にネットワーク活動が活発な期間においては、迅速な処理の可能性を高めるために役立ちます。

ノードは通常、最大150個の最近のブロックに対する優先手数料データをキャッシュします。

## 共通のユースケース

* **動的手数料の見積もり:** 最近成功した手数料を観察して、トランザクションの競争力のある優先手数料を決定します。
* **混雑分析:** 支払われている優先手数料のレベルを見ることで、現在のネットワーク混雑の状態を理解します。
* **ウォレット統合:** 最近のネットワーク状況に基づいて、ユーザーに適切な優先手数料を提案するようウォレットを設定します。
* **アービトラージ・ボット:** アービトラージのような時間に敏感な操作では、最適な優先手数料の設定が迅速な実行に不可欠です。

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

1. **`lockedWritableAccounts`** (`array` of `string`、オプション):
   * トランザクションが書きロックすることを意図しているアカウントのBase-58エンコードされた公開鍵の配列。
   * 最大128のアドレスを提供できます。
   * 提供された場合、メソッドは指定されたアカウントすべてを書き可能としてロックしたトランザクションによって支払われた優先手数料を返します。
   * 提供されない場合や空の配列が渡された場合、特定のアカウントセットに限定されない、最近のブロック全体で観察された優先手数料のより一般的なビューを返します。

## レスポンス構造

JSON-RPCレスポンスの`result`フィールドは、優先手数料オブジェクトの配列です。各オブジェクトは特定の最近のスロットからの手数料を詳細に示し、以下の構造を持ちます。

* **`slot`** (`u64`): このスロットで手数料データに寄与するトランザクションが処理されたスロット番号。
* **`prioritizationFee`** (`u64`): このスロットで（および`lockedWritableAccounts`フィルターに一致する場合）少なくとも1つのトランザクションによって支払われた最小の優先手数料（マイクロLamports/計算ユニット）。`0`の値は、基礎的な手数料を超えた追加の優先手数料が支払われなかったことを意味するか、指定されたアカウントに対してノードが観察しなかったことを意味します。

## 例

### 1. 最近のグローバル優先手数料を取得する

特定のロックアカウントを指定せずに、最近の優先手数料の一般的なリストを取得します。

<CodeGroup>
  ```bash cURL theme={"system"}
  # Replace <api-key> with your Helius API key
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getRecentPrioritizationFees",
      "params": [[]] # Empty array for global fees
    }'
  ```

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

  async function fetchGlobalPrioritizationFees() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    try {
      // Pass an empty array or omit the parameter for global fees
      const fees = await connection.getRecentPrioritizationFees([]); 
      if (fees && fees.length > 0) {
        console.log(`Fetched ${fees.length} recent prioritization fee samples (global):`);
        fees.forEach((feeInfo, index) => {
          console.log(`--- Sample ${index + 1} ---`);
          console.log(`  Slot: ${feeInfo.slot}`);
          console.log(`  Prioritization Fee (micro-lamports/CU): ${feeInfo.prioritizationFee}`);
        });
        // Example: Calculate the median of non-zero fees
        const nonZeroFees = fees.filter(f => f.prioritizationFee > 0).map(f => f.prioritizationFee).sort((a,b) => a - b);
        if (nonZeroFees.length > 0) {
          const mid = Math.floor(nonZeroFees.length / 2);
          const medianFee = nonZeroFees.length % 2 !== 0 ? nonZeroFees[mid] : (nonZeroFees[mid - 1] + nonZeroFees[mid]) / 2;
          console.log(`\nMedian non-zero priority fee: ${medianFee} micro-lamports/CU`);
        }
      } else {
        console.log('No recent prioritization fee data returned.');
      }
    } catch (error) {
      console.error('Error fetching global prioritization fees:', error);
    }
  }

  fetchGlobalPrioritizationFees();
  ```
</CodeGroup>

### 2. 特定の書き込み可能アカウントの最近の優先手数料を取得する

2つの特定のアカウントを書きロックする必要があるトランザクションに関連する優先手数料を取得します。

<CodeGroup>
  ```bash cURL theme={"system"}
  # Replace <api-key> with your Helius API key
  # Replace with actual public keys you are interested in
  curl https://mainnet.helius-rpc.com/?api-key=<api-key> -X POST -H "Content-Type: application/json" -d \
    '{
      "jsonrpc": "2.0",
      "id": 1,
      "method": "getRecentPrioritizationFees",
      "params": [[
        "Vote111111111111111111111111111111111111111", 
        "Stake11111111111111111111111111111111111111"
      ]]
    }'
  ```

  ```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 fetchPrioritizationFeesForAccounts() {
    const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=<api-key>');
    
    // Replace with actual public keys your transaction will lock
    const accountsToLock = [
      new PublicKey('Vote111111111111111111111111111111111111111'),
      new PublicKey('Stake11111111111111111111111111111111111111')
    ];

    try {
      const fees = await connection.getRecentPrioritizationFees(accountsToLock.map(pk => pk.toBase58()));
      if (fees && fees.length > 0) {
        console.log(`Fetched ${fees.length} recent prioritization fee samples for specified accounts:`);
        fees.forEach((feeInfo, index) => {
          console.log(`--- Sample ${index + 1} ---`);
          console.log(`  Slot: ${feeInfo.slot}`);
          console.log(`  Prioritization Fee (micro-lamports/CU): ${feeInfo.prioritizationFee}`);
        });
      } else {
        console.log('No recent prioritization fee data returned for the specified accounts.');
      }
    } catch (error) {
      console.error('Error fetching prioritization fees for accounts:', error);
    }
  }

  fetchPrioritizationFeesForAccounts();
  ```
</CodeGroup>

## 開発者向けヒント

* **手数料単位:** 優先手数料は、マイクロLamports（0.000001 Lamports）/計算ユニット（CU）として表現されます。
* **キャッシュウィンドウ:** RPCノードは通常、約150ブロックの間にこれらの手数料をキャッシュします。これは比較的短い履歴ウィンドウ（約1-2分）を見ていることになります。
* **ゼロ手数料:** `prioritizationFee`が`0`であることは、必ずしも手数料が支払われなかったことを意味するのではなく、指定されたスロットとアカウントに対して、サンプリングされたトランザクションが優先手数料を含まなかったか、ノードが重要と考える閾値を下回っていたことを意味します。
* **戦略的使用:** 最高の最近の手数料を選ぶだけではなく、分布（例：中央値、非ゼロ手数料の75パーセンタイル）を分析してコスト効率的な選択を行います。ブロックがすでに高優先度のトランザクションでいっぱいである場合、過剰な支払いは必ずしも迅速な含有を保証するものではありません。
* **計算ユニット:** あなたのトランザクションの総優先手数料は`prioritizationFee_per_CU * your_transaction_compute_units`になります。トランザクションの計算ユニット制限 (`ComputeBudgetProgram.setComputeUnitLimit`) と価格 (`ComputeBudgetProgram.setComputeUnitPrice`) も設定する必要があります。

`getRecentPrioritizationFees`を効果的に使用することで、動的なネットワーク条件におけるトランザクションの確認の信頼性を大幅に向上させることができます。
