> ## 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 giao dịch được tuần tự hóa

> Nhận kết quả ước tính phí ưu tiên Solana chính xác nhất bằng giao dịch được tuần tự hóa với Helius Priority Fee API. Phù hợp với các ứng dụng production.

<Info>
  **Phương thức chính xác nhất**: Nhận kết quả ước tính phí ưu tiên có độ chính xác cao nhất bằng cách phân tích chính xác giao dịch của bạn. Nên dùng cho các ứng dụng production cần độ chính xác tối đa.
</Info>

## Tổng quan

Giao dịch được tuần tự hóa cung cấp kết quả ước tính phí chính xác nhất vì API có thể phân tích chính xác các tài khoản và thao tác sẽ được thực hiện trong giao dịch của bạn.

<CardGroup cols={2}>
  <Card title="Why Use Serialized Transactions" icon="bullseye">
    * **Độ chính xác cao nhất** - Phân tích chính xác các thao tác
    * **Phân tích chi tiết** - Các mẫu riêng cho từng chỉ thị
    * **Ước tính thực tế** - Phản ánh giao dịch thực tế
    * **Sẵn sàng cho production** - Được xây dựng cho các ứng dụng quan trọng
  </Card>

  <Card title="Best For" icon="bullseye-pointer">
    * Ứng dụng production
    * Giao dịch phức tạp
    * Thao tác quan trọng
    * Trường hợp cần độ chính xác tối đa
  </Card>
</CardGroup>

## Ưu điểm so với khóa tài khoản

<Tabs>
  <Tab title="Accuracy Benefits">
    <CardGroup cols={1}>
      <Card title="Instruction-Specific Analysis" icon="code">
        API có thể phân tích các thao tác cụ thể và mẫu phí trước đây của chúng, không chỉ hoạt động của tài khoản.
      </Card>

      <Card title="Transaction Size Awareness" icon="expand">
        Xem xét kích thước và độ phức tạp thực tế của giao dịch để đưa ra kết quả ước tính chính xác hơn.
      </Card>

      <Card title="Read-Only Account Handling" icon="eye">
        Phân tích tốt hơn cả tài khoản có thể ghi và tài khoản chỉ đọc trong ngữ cảnh giao dịch.
      </Card>
    </CardGroup>
  </Tab>

  <Tab title="Real-World Benefits">
    ### Giao dịch DeFi

    Ước tính chính xác hơn cho các thao tác hoán đổi phức tạp

    ### Đúc NFT

    Ước tính tốt hơn cho các giao dịch đúc có siêu dữ liệu cụ thể

    ### Giao dịch có nhiều chỉ thị

    Phí chính xác cho các thao tác nhiều bước phức tạp

    ### Tương tác với chương trình

    Ước tính tốt hơn cho các lệnh gọi chương trình cụ thể
  </Tab>
</Tabs>

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

<Steps>
  <Step title="Build Your Transaction">
    Tạo giao dịch với tất cả chỉ thị (ngoại trừ phí ưu tiên)
  </Step>

  <Step title="Serialize the Transaction">
    Chuyển đổi giao dịch sang định dạng tuần tự hóa
  </Step>

  <Step title="Get Fee Estimate">
    Gọi Priority Fee API bằng giao dịch được tuần tự hóa
  </Step>

  <Step title="Apply Priority Fee">
    Thêm chỉ thị phí ưu tiên và gửi giao dịch
  </Step>
</Steps>

### Ví dụ bắt đầu nhanh

<CodeGroup>
  ```javascript JavaScript theme={"system"}
  import { 
    Connection, 
    PublicKey, 
    Transaction, 
    SystemProgram, 
    ComputeBudgetProgram 
  } from "@solana/web3.js";
  import bs58 from "bs58";

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

  // 1. Build your transaction (without priority fee)
  const transaction = new Transaction();
  const transferIx = SystemProgram.transfer({
    fromPubkey: senderKeypair.publicKey,
    toPubkey: recipientPublicKey,
    lamports: 1000000, // 0.001 SOL
  });
  transaction.add(transferIx);

  // 2. Set required fields and serialize
  transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
  transaction.feePayer = senderKeypair.publicKey;
  const serializedTx = bs58.encode(transaction.serialize());

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

  // 4. Add priority fee and send
  transaction.instructions = []; // Reset
  transaction.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityFee }));
  transaction.add(transferIx);
  transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
  transaction.sign(senderKeypair);
  ```

  ```python Python theme={"system"}
  import requests
  import json
  from solana.transaction import Transaction
  from solana.system_program import transfer, TransferParams

  # Build and serialize transaction
  def get_serialized_transaction():
      # Build your transaction here
      # Return base58 encoded serialized transaction
      pass

  # Get priority fee estimate
  def get_priority_fee_estimate(serialized_tx, 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": [{
                  "transaction": serialized_tx,
                  "options": {
                      "priorityLevel": priority_level,
                      "recommended": True
                  }
              }]
          }
      )
      return response.json()["result"]["priorityFeeEstimate"]

  # Usage
  serialized_tx = get_serialized_transaction()
  fee = get_priority_fee_estimate(serialized_tx, "High")
  print(f"Priority fee: {fee} micro-lamports")
  ```
</CodeGroup>

## Hàm triển khai cốt lõi

Dưới đây là một hàm có thể tái sử dụng để nhận kết quả ước tính phí ưu tiên từ giao dịch được tuần tự hóa:

```javascript theme={"system"}
async function getPriorityFeeEstimate(connection, serializedTransaction, 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: [{
        transaction: serializedTransaction,
        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ụ triển khai hoàn chỉnh

<Tabs>
  <Tab title="Simple Transfer">
    <Accordion title="Expand to see complete example">
      ```javascript theme={"system"}
      const { 
        Connection, 
        PublicKey, 
        Transaction, 
        SystemProgram, 
        ComputeBudgetProgram, 
        sendAndConfirmTransaction,
        Keypair
      } = require("@solana/web3.js");
      const bs58 = require("bs58");

      // Initialize connection and accounts
      const connection = new Connection("https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY");
      const senderKeypair = Keypair.fromSecretKey(bs58.decode("YOUR_PRIVATE_KEY"));
      const receiverPublicKey = new PublicKey("RECIPIENT_PUBLIC_KEY");

      async function sendTransactionWithPriorityFee(amount, priorityLevel = "Medium") {
        // 1. Create transaction with transfer instruction
        const transaction = new Transaction();
        const transferIx = SystemProgram.transfer({
          fromPubkey: senderKeypair.publicKey,
          toPubkey: receiverPublicKey,
          lamports: amount,
        });
        transaction.add(transferIx);
        
        // 2. Set required fields for serialization
        transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
        transaction.feePayer = senderKeypair.publicKey;
        
        // 3. Serialize the transaction
        const serializedTransaction = bs58.encode(transaction.serialize());
        
        // 4. Get priority fee estimate
        const priorityFee = await getPriorityFeeEstimate(connection, serializedTransaction, priorityLevel);
        console.log(`Estimated ${priorityLevel} priority fee: ${priorityFee} micro-lamports`);
        
        // 5. Reset transaction and add priority fee instruction first
        transaction.instructions = [];
        
        // Add priority fee instruction
        const priorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({
          microLamports: priorityFee
        });
        transaction.add(priorityFeeIx);
        
        // Re-add the original transfer instruction
        transaction.add(transferIx);
        
        // 6. Update blockhash and sign
        transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
        transaction.sign(senderKeypair);
        
        // 7. Send the transaction
        try {
          const signature = await sendAndConfirmTransaction(
            connection,
            transaction,
            [senderKeypair],
            { maxRetries: 0 } // Set to 0 for staked connection usage
          );
          console.log(`Transaction successful with signature: ${signature}`);
          return signature;
        } catch (error) {
          console.error("Error sending transaction:", error);
          throw error;
        }
      }

      // Usage
      sendTransactionWithPriorityFee(1000000, "High"); // Send 0.001 SOL with high priority
      ```
    </Accordion>
  </Tab>

  <Tab title="Token Transfer">
    <Accordion title="Expand to see complete example">
      ```javascript theme={"system"}
      const { 
        Connection, 
        PublicKey, 
        Transaction, 
        ComputeBudgetProgram,
        sendAndConfirmTransaction,
        Keypair
      } = require("@solana/web3.js");
      const { 
        createTransferInstruction,
        getAssociatedTokenAddress,
        TOKEN_PROGRAM_ID,
        ASSOCIATED_TOKEN_PROGRAM_ID
      } = require("@solana/spl-token");
      const bs58 = require("bs58");

      async function sendTokenWithPriorityFee(
        connection,
        senderKeypair,
        recipientPublicKey,
        mintAddress,
        amount,
        priorityLevel = "Medium"
      ) {
        // 1. Get token account addresses
        const senderTokenAccount = await getAssociatedTokenAddress(
          mintAddress,
          senderKeypair.publicKey
        );
        
        const recipientTokenAccount = await getAssociatedTokenAddress(
          mintAddress,
          recipientPublicKey
        );
        
        // 2. Create transaction with token transfer instruction
        const transaction = new Transaction();
        const transferIx = createTransferInstruction(
          senderTokenAccount,
          recipientTokenAccount,
          senderKeypair.publicKey,
          amount,
          [],
          TOKEN_PROGRAM_ID
        );
        transaction.add(transferIx);
        
        // 3. Set required fields and serialize
        transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
        transaction.feePayer = senderKeypair.publicKey;
        const serializedTransaction = bs58.encode(transaction.serialize());
        
        // 4. Get priority fee estimate
        const priorityFee = await getPriorityFeeEstimate(connection, serializedTransaction, priorityLevel);
        console.log(`Token transfer priority fee: ${priorityFee} micro-lamports`);
        
        // 5. Reset and rebuild transaction with priority fee
        transaction.instructions = [];
        
        // Add priority fee instruction first
        const priorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({
          microLamports: priorityFee
        });
        transaction.add(priorityFeeIx);
        
        // Re-add the transfer instruction
        transaction.add(transferIx);
        
        // 6. Update blockhash and send
        transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
        transaction.sign(senderKeypair);
        
        const signature = await sendAndConfirmTransaction(
          connection,
          transaction,
          [senderKeypair],
          { maxRetries: 0 }
        );
        
        return signature;
      }
      ```
    </Accordion>
  </Tab>

  <Tab title="Complex Multi-Instruction">
    <Accordion title="Expand to see complete example">
      ```javascript theme={"system"}
      async function complexTransactionWithPriorityFee(connection, keypair) {
        // 1. Build complex transaction with multiple instructions
        const transaction = new Transaction();
        
        // Add multiple instructions
        const createAccountIx = SystemProgram.createAccount({
          fromPubkey: keypair.publicKey,
          newAccountPubkey: newAccountKeypair.publicKey,
          lamports: await connection.getMinimumBalanceForRentExemption(165),
          space: 165,
          programId: TOKEN_PROGRAM_ID,
        });
        
        const initializeAccountIx = createInitializeAccountInstruction(
          newAccountKeypair.publicKey,
          mintAddress,
          keypair.publicKey,
          TOKEN_PROGRAM_ID
        );
        
        const transferIx = SystemProgram.transfer({
          fromPubkey: keypair.publicKey,
          toPubkey: recipientPublicKey,
          lamports: 1000000,
        });
        
        transaction.add(createAccountIx);
        transaction.add(initializeAccountIx);
        transaction.add(transferIx);
        
        // 2. Set required fields and serialize
        transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
        transaction.feePayer = keypair.publicKey;
        const serializedTransaction = bs58.encode(transaction.serialize());
        
        // 3. Get priority fee estimate for complex transaction
        const priorityFee = await getPriorityFeeEstimate(connection, serializedTransaction, "High");
        console.log(`Complex transaction priority fee: ${priorityFee} micro-lamports`);
        
        // 4. Rebuild transaction with priority fee
        transaction.instructions = [];
        
        // Add priority fee instruction first
        const priorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({
          microLamports: priorityFee
        });
        transaction.add(priorityFeeIx);
        
        // Optional: Set compute unit limit for complex transactions
        const computeLimitIx = ComputeBudgetProgram.setComputeUnitLimit({
          units: 400000 // Adjust based on your transaction complexity
        });
        transaction.add(computeLimitIx);
        
        // Re-add all original instructions
        transaction.add(createAccountIx);
        transaction.add(initializeAccountIx);
        transaction.add(transferIx);
        
        // 5. Update blockhash and send
        transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
        transaction.sign(keypair, newAccountKeypair);
        
        const signature = await sendAndConfirmTransaction(
          connection,
          transaction,
          [keypair, newAccountKeypair],
          { maxRetries: 0 }
        );
        
        return signature;
      }
      ```
    </Accordion>
  </Tab>
</Tabs>

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

<AccordionGroup>
  <Accordion title="Include All Priority Levels">
    Nhận kết quả ước tính cho tất cả mức ưu tiên cùng lúc:

    ```javascript theme={"system"}
    async function getAllPriorityLevels(connection, serializedTransaction) {
      const response = await fetch(connection.rpcEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: "1",
          method: "getPriorityFeeEstimate",
          params: [{
            transaction: serializedTransaction,
            options: { 
              includeAllPriorityFeeLevels: true
            }
          }]
        })
      });
      
      const result = await response.json();
      return result.result.priorityFeeLevels;
    }

    // Usage
    const allLevels = await getAllPriorityLevels(connection, serializedTransaction);
    console.log("All priority levels:", allLevels);
    /*
    Output:
    {
      "min": 0,
      "low": 1000, 
      "medium": 5000,
      "high": 15000,
      "veryHigh": 50000,
      "unsafeMax": 100000
    }
    */
    ```
  </Accordion>

  <Accordion title="Include Detailed Analysis">
    Yêu cầu thông tin chi tiết về cách tính phí:

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

    Thông tin này giúp hiểu rõ cách tính phí, bao gồm cả phân tích theo 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:

    ```javascript theme={"system"}
    async function getCustomLookbackEstimate(connection, serializedTransaction, 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: [{
            transaction: serializedTransaction,
            options: { 
              priorityLevel: "Medium",
              lookbackSlots: lookbackSlots  // 1-150, default is 150
            }
          }]
        })
      });
      
      const result = await response.json();
      return result.result.priorityFeeEstimate;
    }

    // Compare different lookback periods
    const recentEstimate = await getCustomLookbackEstimate(connection, serializedTx, 30);
    const longerEstimate = await getCustomLookbackEstimate(connection, serializedTx, 100);

    console.log(`Recent (30 slots): ${recentEstimate} micro-lamports`);
    console.log(`Longer (100 slots): ${longerEstimate} micro-lamports`);
    ```
  </Accordion>
</AccordionGroup>

## Các phương pháp hay nhất

<CardGroup cols={1}>
  <Card title="Transaction Serialization" icon="code">
    **Luôn tuần tự hóa giao dịch thực tế của bạn**, không dùng phiên bản đơn giản hóa

    ```javascript theme={"system"}
    // ✅ Good - serialize actual transaction
    const transaction = new Transaction();
    transaction.add(actualInstruction1);
    transaction.add(actualInstruction2);
    const serialized = bs58.encode(transaction.serialize());
    ```
  </Card>

  <Card title="Instruction Order" icon="list">
    **Bao gồm tất cả chỉ thị ngoại trừ phí ưu tiên** trong giao dịch dùng để ước tính

    ```javascript theme={"system"}
    // ✅ Good - all business logic included
    transaction.add(createAccountIx);
    transaction.add(initializeIx);
    transaction.add(transferIx);

    // ❌ Don't include priority fee in estimation
    ```
  </Card>
</CardGroup>

## Chiến lược xử lý lỗi

<Tabs>
  <Tab title="Robust Error Handling">
    ```javascript theme={"system"}
    class SerializedTransactionFeeEstimator {
      constructor(connection) {
        this.connection = connection;
        this.fallbackFee = 10000; // 10k micro-lamports
      }

      async getEstimate(serializedTransaction, priorityLevel = "Medium") {
        try {
          // Primary attempt with serialized transaction
          return await this.getPrimaryEstimate(serializedTransaction, priorityLevel);
        } catch (error) {
          console.warn("Serialized transaction estimate failed:", error.message);
          
          // Fallback to account-based estimation
          try {
            return await this.getFallbackEstimate(serializedTransaction, priorityLevel);
          } catch (fallbackError) {
            console.warn("Fallback estimate failed:", fallbackError.message);
            return this.getFallbackFee(priorityLevel);
          }
        }
      }

      async getPrimaryEstimate(serializedTransaction, 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: [{
              transaction: serializedTransaction,
              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(serializedTransaction, priorityLevel) {
        // Extract account keys from transaction and use account-based estimation
        const transaction = Transaction.from(bs58.decode(serializedTransaction));
        const accountKeys = transaction.instructions
          .flatMap(ix => [ix.programId, ...ix.keys.map(k => k.pubkey)])
          .map(key => key.toString());

        const uniqueAccountKeys = [...new Set(accountKeys)];
        
        // Use account-based estimation as fallback
        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: uniqueAccountKeys,
              options: { 
                priorityLevel: priorityLevel,
                recommended: true 
              }
            }]
          })
        });

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

      getFallbackFee(priorityLevel) {
        const fallbacks = {
          "Low": 1000,
          "Medium": 5000,
          "High": 15000,
          "VeryHigh": 50000
        };
        
        return fallbacks[priorityLevel] || 5000;
      }
    }

    // Usage
    const estimator = new SerializedTransactionFeeEstimator(connection);
    const fee = await estimator.getEstimate(serializedTransaction, "High");
    ```
  </Tab>

  <Tab title="Simple Error Handling">
    ```javascript theme={"system"}
    async function safeGetPriorityFeeEstimate(connection, serializedTransaction, priorityLevel = "Medium") {
      try {
        return await getPriorityFeeEstimate(connection, serializedTransaction, priorityLevel);
      } catch (error) {
        console.warn(`Priority fee estimation failed: ${error.message}`);
        
        // Extract account keys and fall back to account-based estimation
        try {
          const transaction = Transaction.from(bs58.decode(serializedTransaction));
          const accountKeys = transaction.instructions
            .flatMap(ix => [ix.programId, ...ix.keys.map(k => k.pubkey)])
            .map(key => key.toString());
          
          const uniqueAccountKeys = [...new Set(accountKeys)];
          return await getAccountBasedEstimate(connection, uniqueAccountKeys, priorityLevel);
        } catch (fallbackError) {
          console.warn(`Fallback estimation failed: ${fallbackError.message}`);
          
          // Return reasonable fallback based on priority level
          const fallbacks = {
            "Low": 1000,
            "Medium": 5000,
            "High": 15000,
            "VeryHigh": 50000
          };
          
          return fallbacks[priorityLevel] || 5000;
        }
      }
    }
    ```
  </Tab>
</Tabs>

## Các vấn đề thường gặp và giải pháp

<AccordionGroup>
  <Accordion title="Transaction Serialization Errors">
    **Vấn đề**: Lỗi khi tuần tự hóa giao dịch chưa hoàn chỉnh

    **Giải pháp**: Luôn thiết lập các trường bắt buộc trước khi tuần tự hóa:

    ```javascript theme={"system"}
    // ✅ Always set these fields
    transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
    transaction.feePayer = keypair.publicKey;

    // Then serialize
    const serialized = bs58.encode(transaction.serialize());
    ```
  </Accordion>

  <Accordion title="Stale Blockhash Issues">
    **Vấn đề**: Sử dụng blockhash cũ khiến giao dịch thất bại

    **Giải pháp**: Luôn lấy blockhash mới trước lần gửi cuối cùng:

    ```javascript theme={"system"}
    // Get estimate with temporary blockhash
    const tempBlockhash = (await connection.getLatestBlockhash()).blockhash;
    transaction.recentBlockhash = tempBlockhash;
    const serialized = bs58.encode(transaction.serialize());

    const priorityFee = await getPriorityFeeEstimate(connection, serialized, "Medium");

    // Reset and rebuild with fresh blockhash
    transaction.instructions = [];
    transaction.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityFee }));
    transaction.add(originalInstruction);

    // Get FRESH blockhash before sending
    const freshBlockhash = (await connection.getLatestBlockhash()).blockhash;
    transaction.recentBlockhash = freshBlockhash;
    ```
  </Accordion>

  <Accordion title="Large Transaction Errors">
    **Vấn đề**: Giao dịch quá lớn để tuần tự hóa

    **Giải pháp**: Sử dụng giao dịch có phiên bản hoặc chia thành nhiều giao dịch:

    ```javascript theme={"system"}
    import { VersionedTransaction, TransactionMessage } from "@solana/web3.js";

    // For large transactions, use versioned transactions
    const messageV0 = new TransactionMessage({
      payerKey: keypair.publicKey,
      recentBlockhash: (await connection.getLatestBlockhash()).blockhash,
      instructions: [instruction1, instruction2, instruction3] // Many instructions
    }).compileToV0Message();

    const versionedTransaction = new VersionedTransaction(messageV0);
    const serialized = bs58.encode(versionedTransaction.serialize());
    ```
  </Accordion>
</AccordionGroup>

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

<CardGroup cols={2}>
  <Card title="Use Serialized Transactions" icon="check">
    **Ứng dụng production**

    * Yêu cầu độ chính xác tối đa
    * Giao dịch phức tạp có nhiều chỉ thị
    * Thao tác quan trọng
    * Ứng dụng nhạy cảm với hiệu năng

    **Tình huống phát triển**

    * Kiểm thử tích hợp cuối cùng
    * Tối ưu hóa hiệu năng
    * Triển khai production
  </Card>

  <Card title="Use Account Keys" icon="info">
    **Phát triển và tạo nguyên mẫu**

    * Ước tính nhanh trong quá trình phát triển
    * Giao dịch đơn giản
    * Lập kế hoạch trước giao dịch
    * Các hạn chế kiến trúc ngăn cản việc tuần tự hóa

    **Tình huống phân tích**

    * Phân tích mẫu phí ở cấp tài khoản
    * Phân tích hàng loạt tài khoản
    * Nghiên cứu thị trường nhanh
  </Card>
</CardGroup>

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

<CardGroup cols={2}>
  <Card title="Account Keys Method" icon="key" href="/docs/vi/priority-fee/estimating-fees-using-account-keys">
    Phương thức nâng cao sử dụng khóa tài khoản cho các trường hợp sử dụng chuyên biệt
  </Card>

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