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

# Ước tính phí ưu tiên Solana: Phương thức khóa tài khoản

> Ước tính phí ưu tiên Solana bằng khóa tài khoản với Helius Priority Fee API. Ước tính phí nhanh để phân tích trước giao dịch và thực hiện thao tác hàng loạt.

<Info>
  **Phương thức nâng cao**: Nhận thông tin ước tính phí ưu tiên bằng khóa tài khoản cho các trường hợp sử dụng chuyên biệt như phân tích trước giao dịch, thao tác hàng loạt và nghiên cứu mẫu tài khoản.
</Info>

## Tổng quan

Phương thức khóa tài khoản là một giải pháp thay thế đơn giản hơn cho việc tuần tự hóa giao dịch khi bạn cần ước tính phí nhanh hoặc muốn ước tính phí trước khi tạo giao dịch hoàn chỉnh.

<CardGroup cols={2}>
  <Card title="Advanced Use Cases" icon="key">
    * Phân tích trước giao dịch
    * Thao tác tài khoản hàng loạt
    * Nghiên cứu thị trường và các mẫu
    * Kiến trúc chuyên biệt
  </Card>

  <Card title="Trade-offs" icon="scale-unbalanced-flip">
    * Kém chính xác hơn giao dịch được tuần tự hóa
    * Không phân tích theo từng chỉ thị
    * Phù hợp nhất với các mẫu ở cấp tài khoản
  </Card>
</CardGroup>

<Warning>
  **Khuyến nghị**: Với hầu hết ứng dụng, hãy sử dụng [phương thức giao dịch được tuần tự hóa](/docs/vi/priority-fee/estimating-fees-using-serialized-transaction). Phương thức khóa tài khoản này dành cho các trường hợp sử dụng chuyên biệt cần phân tích ở cấp tài khoản hoặc lập kế hoạch trước giao dịch.
</Warning>

## Khi nào nên sử dụng khóa tài khoản

<Tabs>
  <Tab title="Ideal Use Cases">
    <CardGroup cols={2}>
      <Card title="Pre-transaction Planning" icon="calendar">
        Nhận thông tin ước tính phí trước khi tạo giao dịch hoàn chỉnh
      </Card>

      <Card title="Simplified Integration" icon="puzzle-piece">
        Khi kiến trúc của bạn khiến việc tuần tự hóa giao dịch trở nên khó khăn
      </Card>

      <Card title="Quick Market Analysis" icon="chart-line">
        Phân tích mẫu phí của các tài khoản cụ thể mà không cần tạo giao dịch
      </Card>

      <Card title="Multi-account Analysis" icon="users">
        Tìm hiểu riêng biệt các mẫu phí trên nhiều tài khoản
      </Card>
    </CardGroup>
  </Tab>

  <Tab title="Specialized Scenarios">
    **Nghiên cứu và phân tích**: Khi nghiên cứu mẫu phí trên nhiều tài khoản và chương trình khác nhau

    **Thao tác hàng loạt**: Khi phân tích đồng thời mẫu phí trên nhiều tài khoản

    **Lập kế hoạch trước**: Để ước tính chi phí trước khi xây dựng quy trình giao dịch phức tạp

    **Kiến trúc tùy chỉnh**: Khi các giới hạn của hệ thống ngăn cản việc tuần tự hóa giao dịch
  </Tab>
</Tabs>

## Bắt đầu nhanh

<Steps>
  <Step title="Identify Accounts">
    Xác định những tài khoản sẽ tham gia vào giao dịch của bạn
  </Step>

  <Step title="Call the API">
    Gửi yêu cầu với các khóa tài khoản và mức ưu tiên mong muốn
  </Step>

  <Step title="Apply the Fee">
    Sử dụng kết quả ước tính để đặt phí ưu tiên trong giao dịch
  </Step>
</Steps>

### Ví dụ cơ bản

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

## Hướng dẫn triển khai

### Hàm cốt lõi

Dưới đây là một hàm có thể tái sử dụng để nhận thông tin ước tính phí ưu tiên:

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

### Ví dụ hoàn chỉnh với nhiều mức ưu tiên

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

## Loại tài khoản và chiến lược

<Tabs>
  <Tab title="Program Accounts">
    Các tài khoản chương trình có lưu lượng lớn thường có phí ưu tiên cao hơn do cạnh tranh.

    ```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>
      **Hành vi dự kiến**: Phí cao hơn do khối lượng giao dịch lớn và mức độ cạnh tranh cao.
    </Note>
  </Tab>

  <Tab title="User Wallets">
    Ví người dùng đang hoạt động có thể có các mẫu phí khác nhau tùy theo hoạt động của chúng.

    ```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>
      **Mẹo chuyên môn**: Bao gồm cả ví người gửi và người nhận để có kết quả ước tính chính xác hơn.
    </Tip>
  </Tab>

  <Tab title="Token Accounts">
    Các tài khoản token cụ thể có thể thể hiện những mẫu khác nhau tùy theo mức độ phổ biến của token.

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

## Tùy chọn cấu hình nâng cao

<AccordionGroup>
  <Accordion title="Empty Slot Evaluation">
    Tùy chọn `evaluateEmptySlotAsZero` đặc biệt hữu ích cho các kết quả ước tính dựa trên tài khoản:

    ```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>
      Khi `true` (mặc định), các slot không có giao dịch được xem là có phí bằng 0 thay vì bị loại trừ. Điều này cung cấp kết quả ước tính cân bằng hơn cho các tài khoản có ít hoạt động.
    </Note>
  </Accordion>

  <Accordion title="Include Details">
    Yêu cầu thông tin chi tiết về mẫu phí của từng tài khoản:

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

    Thao tác này trả về thông tin bổ sung về cách tính phí cho từng tài khoản.
  </Accordion>

  <Accordion title="Custom Lookback Period">
    Điều chỉnh số lượng slot được phân tích để ước tính phí:

    ```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>
      **Khoảng xem lại ngắn hơn**: Dữ liệu gần đây hơn nhưng có thể biến động

      **Khoảng xem lại dài hơn**: Ổn định hơn và có thêm bối cảnh lịch sử
    </Tip>
  </Accordion>
</AccordionGroup>

## Phương pháp hay nhất để lựa chọn tài khoản

<CardGroup cols={1}>
  <Card title="Include Writable Accounts" icon="pen-to-square">
    **Ưu tiên**: Tập trung vào các tài khoản sẽ được sửa đổi

    ```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">
    **Bối cảnh**: Bao gồm các tài khoản chương trình có liên quan

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

## Xử lý lỗi và phương án dự phòng

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

## Hạn chế và lưu ý

<Warning>
  **Hạn chế của phương thức dựa trên tài khoản:**

  1. **Kém chính xác hơn với tài khoản chỉ đọc** - Thuật toán tập trung vào các tài khoản có thể ghi
  2. **Không phân tích theo từng chỉ thị** - Không thể xem xét các thao tác cụ thể
  3. **Phụ thuộc vào hoạt động của tài khoản** - Kém chính xác hơn với các tài khoản không hoạt động
  4. **Không xem xét kích thước giao dịch** - Không tính đến độ phức tạp của giao dịch
</Warning>

<Note>
  **Khi nào nên chuyển sang giao dịch được tuần tự hóa:**

  * Ứng dụng production cần độ chính xác cao nhất
  * Giao dịch phức tạp có nhiều chỉ thị
  * Khi mẫu phí theo từng chỉ thị có ý nghĩa quan trọng
  * Ứng dụng yêu cầu hiệu năng cao
</Note>

## Tài nguyên liên quan

<CardGroup cols={2}>
  <Card title="Serialized Transactions" icon="file-code" href="/docs/vi/priority-fee/estimating-fees-using-serialized-transaction">
    Phương thức chính xác hơn sử dụng quy trình tuần tự hóa toàn bộ giao dịch
  </Card>

  <Card title="API Reference" icon="book" href="/docs/vi/api-reference/priority-fee/getpriorityfeeestimate">
    Tài liệu API và các tham số đầy đủ
  </Card>
</CardGroup>
