> ## 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 네트워크의 최근 블록에서 지불된 우선 수수료에 대한 통찰력을 제공합니다. 이러한 수수료를 조사함으로써 개발자는 특히 네트워크 활동이 많은 시기에 거래가 신속하게 처리될 가능성을 높이기 위해 거래에 추가할 추가 수수료([우선 수수료](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` 필터와 일치할 경우). `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. 특정 쓰기 가능한 계정에 대한 최근 우선 수수료 가져오기

이 예제는 두 개의 특정 계정을 쓰기 잠금해야 하는 거래에 대한 관련 우선 수수료를 가져옵니다.

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

## 개발자 팁

* **수수료 단위:** 우선 수수료는 컴퓨트 유닛(CU)당 마이크로-램포츠(0.000001 램포츠)로 표현됩니다.
* **캐시 창:** RPC 노드는 일반적으로 이러한 수수료를 약 150 블록 동안 캐싱합니다. 이는 상대적으로 짧은 역사적 창(대략 1-2분)을 보고 있다는 것을 의미합니다.
* **수수료 없음:** `prioritizationFee`이 `0`인 경우 반드시 수수료가 지불되지 않았다는 것을 의미하는 것은 아니지만, 해당 슬롯 및 계정에 대해 샘플링된 거래가 우선 수수료를 포함하지 않았거나, 노드에서 중요하다고 간주하는 임계값 이하일 수 있습니다.
* **전략적 사용:** 단순히 최근 가장 높은 수수료를 선택하지 마세요. 분포(예: 중간 값, 75번째 백분위의 비영 제로 수수료)를 분석하여 비용 효과적인 선택을 하세요. 지나치게 지불하는 것은 이미 높은 우선 순위의 거래로 가득 찬 블록에서는 더 빠른 포함을 보장하지 않습니다.
* **컴퓨트 유닛:** 거래에 대한 총 우선 수수료는 `prioritizationFee_per_CU * your_transaction_compute_units`입니다. 또한 거래의 컴퓨트 유닛 제한(`ComputeBudgetProgram.setComputeUnitLimit`)과 가격(`ComputeBudgetProgram.setComputeUnitPrice`)을 설정해야 합니다.

`getRecentPrioritizationFees`를 효과적으로 사용하면 동적 네트워크 조건에서 거래 확인 신뢰성을 크게 향상시킬 수 있습니다.
