> ## 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 по ключам аккаунтов с помощью Helius Priority Fee API. Быстрая оценка комиссий для анализа перед транзакцией и пакетных операций.

<Info>
  **Расширенный метод**: получайте оценки приоритетной комиссии по ключам аккаунтов для специализированных сценариев, таких как анализ перед транзакцией, пакетные операции и исследование закономерностей аккаунтов.
</Info>

## Обзор

Метод ключей аккаунтов — более простая альтернатива сериализации транзакций, когда нужно быстро оценить комиссию или сделать это до формирования полной транзакции.

<CardGroup cols={2}>
  <Card title="Advanced Use Cases" icon="key">
    * Анализ перед транзакцией
    * Пакетные операции с аккаунтами
    * Исследование рынка и закономерностей
    * Специализированные архитектуры
  </Card>

  <Card title="Trade-offs" icon="scale-unbalanced-flip">
    * Меньшая точность по сравнению с сериализованными транзакциями
    * Нет анализа отдельных инструкций
    * Лучше всего подходит для закономерностей на уровне аккаунтов
  </Card>
</CardGroup>

<Warning>
  **Рекомендация**: для большинства приложений вместо этого используйте [метод сериализованных транзакций](/docs/ru/priority-fee/estimating-fees-using-serialized-transaction). Метод ключей аккаунтов предназначен для специализированных сценариев, требующих анализа на уровне аккаунтов или планирования перед транзакцией.
</Warning>

## Когда следует использовать ключи аккаунтов

<Tabs>
  <Tab title="Ideal Use Cases">
    <CardGroup cols={2}>
      <Card title="Pre-transaction Planning" icon="calendar">
        Получайте оценки комиссии до формирования полных транзакций
      </Card>

      <Card title="Simplified Integration" icon="puzzle-piece">
        Используйте, если ваша архитектура затрудняет сериализацию транзакций
      </Card>

      <Card title="Quick Market Analysis" icon="chart-line">
        Анализируйте закономерности комиссий для определенных аккаунтов без формирования транзакций
      </Card>

      <Card title="Multi-account Analysis" icon="users">
        Независимо изучайте закономерности комиссий для нескольких аккаунтов
      </Card>
    </CardGroup>
  </Tab>

  <Tab title="Specialized Scenarios">
    **Исследование и анализ**: при изучении закономерностей комиссий для различных аккаунтов и программ

    **Пакетные операции**: при одновременном анализе закономерностей комиссий для множества аккаунтов

    **Предварительное планирование**: для оценки затрат перед созданием сложных процессов обработки транзакций

    **Нестандартные архитектуры**: когда системные ограничения не позволяют сериализовать транзакции
  </Tab>
</Tabs>

## Быстрый старт

<Steps>
  <Step title="Identify Accounts">
    Определите, какие аккаунты будут задействованы в вашей транзакции
  </Step>

  <Step title="Call the API">
    Отправьте запрос с ключами аккаунтов и нужным уровнем приоритета
  </Step>

  <Step title="Apply the Fee">
    Используйте оценку, чтобы установить приоритетную комиссию в транзакции
  </Step>
</Steps>

### Базовый пример

<CodeGroup>
  ```javascript JavaScript theme={"system"}
  import { ComputeBudgetProgram } from "@solana/web3.js";

  // 1. Identify accounts involved in your transaction
  const accountKeys = [
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // Token program
    "YOUR_WALLET_ADDRESS",                          // Your wallet
    "RECIPIENT_ADDRESS"                             // Recipient
  ];

  // 2. Get priority fee estimate
  const priorityFee = await getPriorityFeeEstimate(connection, accountKeys, "Medium");

  // 3. Add to your transaction
  const priorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({
    microLamports: priorityFee
  });
  transaction.add(priorityFeeIx);
  ```

  ```python Python theme={"system"}
  import requests

  # Get priority fee estimate
  def get_priority_fee_estimate(account_keys, priority_level="Medium"):
      response = requests.post(
          "https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY",
          json={
              "jsonrpc": "2.0",
              "id": "1",
              "method": "getPriorityFeeEstimate",
              "params": [{
                  "accountKeys": account_keys,
                  "options": {
                      "priorityLevel": priority_level,
                      "recommended": True
                  }
              }]
          }
      )
      return response.json()["result"]["priorityFeeEstimate"]

  # Usage
  accounts = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]
  fee = get_priority_fee_estimate(accounts, "High")
  print(f"Priority fee: {fee} micro-lamports")
  ```
</CodeGroup>

## Руководство по реализации

### Основная функция

Ниже приведена переиспользуемая функция для получения оценок приоритетной комиссии:

```javascript theme={"system"}
async function getPriorityFeeEstimate(connection, accountKeys, priorityLevel = "Medium") {
  const response = await fetch(connection.rpcEndpoint, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      jsonrpc: "2.0",
      id: "1",
      method: "getPriorityFeeEstimate",
      params: [{
        accountKeys: accountKeys,
        options: { 
          priorityLevel: priorityLevel,
          recommended: true 
        }
      }]
    })
  });
  
  const result = await response.json();
  
  if (result.error) {
    throw new Error(`Fee estimation failed: ${JSON.stringify(result.error)}`);
  }
  
  return result.result.priorityFeeEstimate;
}
```

### Полный пример с несколькими уровнями приоритета

<Accordion title="Expand to see full implementation">
  ```javascript theme={"system"}
  const { 
    Connection, 
    PublicKey, 
    Transaction, 
    ComputeBudgetProgram 
  } = require("@solana/web3.js");

  // Initialize connection
  const connection = new Connection("https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY");

  async function analyzeAccountPriorityFees() {
    // Define accounts involved in your transaction
    const accountKeys = [
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // Token program
      "YOUR_WALLET_ADDRESS",                          // Your wallet
      "TOKEN_ACCOUNT_ADDRESS",                        // Token account
      "RECIPIENT_ADDRESS"                             // Recipient
    ];
    
    try {
      // Get estimates for different priority levels
      const [lowFee, mediumFee, highFee, veryHighFee] = await Promise.all([
        getPriorityFeeEstimate(connection, accountKeys, "Low"),
        getPriorityFeeEstimate(connection, accountKeys, "Medium"), 
        getPriorityFeeEstimate(connection, accountKeys, "High"),
        getPriorityFeeEstimate(connection, accountKeys, "VeryHigh")
      ]);
      
      console.log("Priority Fee Estimates:");
      console.log(`Low:      ${lowFee} micro-lamports`);
      console.log(`Medium:   ${mediumFee} micro-lamports`);
      console.log(`High:     ${highFee} micro-lamports`);
      console.log(`VeryHigh: ${veryHighFee} micro-lamports`);
      
      // Get all levels at once for comparison
      const allLevels = await getAllPriorityLevels(connection, accountKeys);
      console.log("\nAll priority levels:", allLevels);
      
      return {
        low: lowFee,
        medium: mediumFee,
        high: highFee,
        veryHigh: veryHighFee,
        allLevels
      };
    } catch (error) {
      console.error("Error getting priority fees:", error);
      throw error;
    }
  }

  // Helper function to get all priority levels
  async function getAllPriorityLevels(connection, accountKeys) {
    const response = await fetch(connection.rpcEndpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: "1",
        method: "getPriorityFeeEstimate",
        params: [{
          accountKeys: accountKeys,
          options: { 
            includeAllPriorityFeeLevels: true
          }
        }]
      })
    });
    
    const result = await response.json();
    
    if (result.error) {
      throw new Error(`Fee estimation failed: ${JSON.stringify(result.error)}`);
    }
    
    return result.result.priorityFeeLevels;
  }

  // Run the analysis
  analyzeAccountPriorityFees();
  ```
</Accordion>

## Типы аккаунтов и стратегии

<Tabs>
  <Tab title="Program Accounts">
    Для аккаунтов программ с большим объемом операций приоритетные комиссии обычно выше из-за конкуренции.

    ```javascript theme={"system"}
    // Popular program accounts
    const programAccounts = [
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // Token program
      "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", // Associated token program
      "M2mx93ekt1fmXSVkTrUL9xVFHkmME8HTUi5Cyc5aF7K"  // Metaplex program
    ];

    const programFees = await getPriorityFeeEstimate(connection, programAccounts, "Medium");
    console.log(`Program account fees: ${programFees} micro-lamports`);
    ```

    <Note>
      **Ожидаемое поведение**: комиссии выше из-за большого объема транзакций и конкуренции.
    </Note>
  </Tab>

  <Tab title="User Wallets">
    Закономерности комиссий для активных пользовательских кошельков могут различаться в зависимости от их активности.

    ```javascript theme={"system"}
    // Active user wallets
    const userWallets = [
      "USER_WALLET_1", // Active trader
      "USER_WALLET_2"  // Regular user
    ];

    const walletFees = await getPriorityFeeEstimate(connection, userWallets, "Medium");
    console.log(`User wallet fees: ${walletFees} micro-lamports`);
    ```

    <Tip>
      **Совет**: включите кошельки отправителя и получателя, чтобы получить более точные оценки.
    </Tip>
  </Tab>

  <Tab title="Token Accounts">
    Закономерности для определенных аккаунтов токенов могут различаться в зависимости от популярности токена.

    ```javascript theme={"system"}
    // Popular token accounts
    const tokenAccounts = [
      "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC mint
      "So11111111111111111111111111111111111111112",  // SOL mint
      "YOUR_TOKEN_ACCOUNT"                            // Your specific token account
    ];

    const tokenFees = await getPriorityFeeEstimate(connection, tokenAccounts, "Medium");
    ```
  </Tab>
</Tabs>

## Расширенные параметры конфигурации

<AccordionGroup>
  <Accordion title="Empty Slot Evaluation">
    Параметр `evaluateEmptySlotAsZero` особенно полезен для оценок на основе аккаунтов:

    ```javascript theme={"system"}
    async function compareEmptySlotHandling(accountKeys) {
      const withEmptyAsZero = await fetch(connection.rpcEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: "1",
          method: "getPriorityFeeEstimate",
          params: [{
            accountKeys: accountKeys,
            options: { 
              priorityLevel: "Medium",
              evaluateEmptySlotAsZero: true // Default: true
            }
          }]
        })
      });

      const withoutEmptyAsZero = await fetch(connection.rpcEndpoint, {
        method: "POST", 
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: "1",
          method: "getPriorityFeeEstimate", 
          params: [{
            accountKeys: accountKeys,
            options: {
              priorityLevel: "Medium",
              evaluateEmptySlotAsZero: false
            }
          }]
        })
      });
      
      const result1 = await withEmptyAsZero.json();
      const result2 = await withoutEmptyAsZero.json();
      
      console.log(`With empty as zero: ${result1.result.priorityFeeEstimate}`);
      console.log(`Without empty as zero: ${result2.result.priorityFeeEstimate}`);
    }
    ```

    <Note>
      При значении `true` (по умолчанию) слотам без транзакций присваивается нулевая комиссия вместо их исключения. Это позволяет получать более сбалансированные оценки для аккаунтов с низкой активностью.
    </Note>
  </Accordion>

  <Accordion title="Include Details">
    Запросите подробную информацию о закономерностях комиссий для каждого аккаунта:

    ```javascript theme={"system"}
    async function getDetailedFeeEstimate(connection, accountKeys) {
      const response = await fetch(connection.rpcEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: "1",
          method: "getPriorityFeeEstimate",
          params: [{
            accountKeys: accountKeys,
            options: { 
              includeDetails: true,
              priorityLevel: "Medium"
            }
          }]
        })
      });
      
      const result = await response.json();
      console.log("Detailed fee analysis:", result.result);
      return result.result;
    }
    ```

    В ответе будет дополнительная информация о том, как рассчитывались комиссии для каждого аккаунта.
  </Accordion>

  <Accordion title="Custom Lookback Period">
    Настройте количество слотов, анализируемых для оценки комиссии:

    ```javascript theme={"system"}
    async function getCustomLookbackEstimate(accountKeys, lookbackSlots = 50) {
      const response = await fetch(connection.rpcEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: "1",
          method: "getPriorityFeeEstimate",
          params: [{
            accountKeys: accountKeys,
            options: { 
              priorityLevel: "Medium",
              lookbackSlots: lookbackSlots  // 1-150, default is 150
            }
          }]
        })
      });
      
      const result = await response.json();
      return result.result.priorityFeeEstimate;
    }

    // Compare different lookback periods
    const shortTerm = await getCustomLookbackEstimate(accountKeys, 50);   // Recent trends
    const longTerm = await getCustomLookbackEstimate(accountKeys, 150);   // Historical average

    console.log(`Short-term estimate: ${shortTerm} micro-lamports`);
    console.log(`Long-term estimate: ${longTerm} micro-lamports`);
    ```

    <Tip>
      **Короткий период анализа**: более свежие, но потенциально волатильные данные

      **Длинный период анализа**: более стабильный исторический контекст
    </Tip>
  </Accordion>
</AccordionGroup>

## Рекомендации по выбору аккаунтов

<CardGroup cols={1}>
  <Card title="Include Writable Accounts" icon="pen-to-square">
    **Приоритет**: сосредоточьтесь на аккаунтах, которые будут изменены

    ```javascript theme={"system"}
    const writableAccounts = [
      "YOUR_WALLET",        // Paying fees
      "TOKEN_ACCOUNT",      // Being modified  
      "RECIPIENT_ACCOUNT"   // Receiving tokens
    ];
    ```
  </Card>

  <Card title="Add Key Programs" icon="gear">
    **Контекст**: включите аккаунты соответствующих программ

    ```javascript theme={"system"}
    const programAccounts = [
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", // Token program
      "CUSTOM_PROGRAM_ID"                           // Your program
    ];
    ```
  </Card>
</CardGroup>

## Обработка ошибок и резервные варианты

<CodeGroup>
  ```javascript Robust Implementation theme={"system"}
  class AccountBasedFeeEstimator {
    constructor(connection) {
      this.connection = connection;
      this.fallbackFee = 10000; // 10k micro-lamports fallback
    }

    async getEstimate(accountKeys, priorityLevel = "Medium") {
      try {
        // Primary attempt
        const estimate = await this.getPrimaryEstimate(accountKeys, priorityLevel);
        return estimate;
      } catch (error) {
        console.warn("Primary estimate failed:", error.message);
        
        // Fallback to different configuration
        try {
          return await this.getFallbackEstimate(accountKeys, priorityLevel);
        } catch (fallbackError) {
          console.warn("Fallback estimate failed:", fallbackError.message);
          return this.fallbackFee;
        }
      }
    }

    async getPrimaryEstimate(accountKeys, priorityLevel) {
      const response = await fetch(this.connection.rpcEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: "1",
          method: "getPriorityFeeEstimate",
          params: [{
            accountKeys: accountKeys,
            options: { 
              priorityLevel: priorityLevel,
              recommended: true 
            }
          }]
        })
      });

      const result = await response.json();
      if (result.error) {
        throw new Error(result.error.message);
      }
      
      return result.result.priorityFeeEstimate;
    }

    async getFallbackEstimate(accountKeys, priorityLevel) {
      // Try with fewer accounts or different settings
      const coreAccounts = accountKeys.slice(0, 3); // Take first 3 accounts
      
      const response = await fetch(this.connection.rpcEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: "1",
          method: "getPriorityFeeEstimate",
          params: [{
            accountKeys: coreAccounts,
            options: { 
              priorityLevel: "Medium", // Use medium as fallback
              evaluateEmptySlotAsZero: true
            }
          }]
        })
      });

      const result = await response.json();
      if (result.error) {
        throw new Error(result.error.message);
      }
      
      return result.result.priorityFeeEstimate;
    }
  }

  // Usage
  const estimator = new AccountBasedFeeEstimator(connection);
  const fee = await estimator.getEstimate(accountKeys, "High");
  ```

  ```javascript Simple Error Handling theme={"system"}
  async function safeGetPriorityFee(accountKeys, priorityLevel = "Medium") {
    try {
      return await getPriorityFeeEstimate(connection, accountKeys, priorityLevel);
    } catch (error) {
      console.warn(`Priority fee estimation failed: ${error.message}`);
      
      // Return reasonable fallback based on priority level
      const fallbacks = {
        "Low": 1000,
        "Medium": 5000,
        "High": 15000,
        "VeryHigh": 50000
      };
      
      return fallbacks[priorityLevel] || 5000;
    }
  }
  ```
</CodeGroup>

## Ограничения и особенности

<Warning>
  **Ограничения метода на основе аккаунтов:**

  1. **Меньшая точность для аккаунтов только для чтения** — алгоритм ориентирован на записываемые аккаунты
  2. **Нет анализа отдельных инструкций** — невозможно учитывать конкретные операции
  3. **Зависимость от активности аккаунта** — меньшая точность для неактивных аккаунтов
  4. **Не учитывается размер транзакции** — сложность транзакции не принимается во внимание
</Warning>

<Note>
  **Когда следует перейти на сериализованные транзакции:**

  * Для рабочих приложений, требующих максимальной точности
  * Для сложных транзакций с несколькими инструкциями
  * Когда важны закономерности комиссий для отдельных инструкций
  * Для приложений с критичными требованиями к производительности
</Note>

## Связанные ресурсы

<CardGroup cols={2}>
  <Card title="Serialized Transactions" icon="file-code" href="/docs/ru/priority-fee/estimating-fees-using-serialized-transaction">
    Более точный метод с полной сериализацией транзакций
  </Card>

  <Card title="API Reference" icon="book" href="/docs/ru/api-reference/priority-fee/getpriorityfeeestimate">
    Полная документация API и параметры
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.