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

# Estimación de comisiones de prioridad de Solana: método de claves de cuenta

> Estima las comisiones de prioridad de Solana mediante claves de cuenta con la API de comisiones de prioridad de Helius. Obtén estimaciones rápidas para análisis previos a una transacción y operaciones por lotes.

<Info>
  **Método avanzado**: Obtén estimaciones de comisiones de prioridad mediante claves de cuenta para casos de uso especializados, como análisis previos a una transacción, operaciones por lotes e investigación de patrones de cuentas.
</Info>

## Descripción general

El método de claves de cuenta ofrece una alternativa más sencilla a la serialización de transacciones cuando necesitas estimaciones rápidas de comisiones o quieres estimarlas antes de construir la transacción completa.

<CardGroup cols={2}>
  <Card title="Advanced Use Cases" icon="key">
    * Análisis previo a una transacción
    * Operaciones de cuentas por lotes
    * Investigación y patrones de mercado
    * Arquitecturas especializadas
  </Card>

  <Card title="Trade-offs" icon="scale-unbalanced-flip">
    * Menos preciso que las transacciones serializadas
    * Sin análisis específico de instrucciones
    * Ideal para patrones a nivel de cuenta
  </Card>
</CardGroup>

<Warning>
  **Recomendación**: Para la mayoría de las aplicaciones, usa en su lugar el [método de transacción serializada](/docs/es/priority-fee/estimating-fees-using-serialized-transaction). Este método de claves de cuenta está diseñado para casos de uso especializados en los que necesitas análisis a nivel de cuenta o planificación previa a una transacción.
</Warning>

## Cuándo usar claves de cuenta

<Tabs>
  <Tab title="Ideal Use Cases">
    <CardGroup cols={2}>
      <Card title="Pre-transaction Planning" icon="calendar">
        Obtén estimaciones de comisiones antes de construir transacciones completas
      </Card>

      <Card title="Simplified Integration" icon="puzzle-piece">
        Cuando tu arquitectura dificulta la serialización de transacciones
      </Card>

      <Card title="Quick Market Analysis" icon="chart-line">
        Analiza patrones de comisiones de cuentas específicas sin construir transacciones
      </Card>

      <Card title="Multi-account Analysis" icon="users">
        Comprende de forma independiente los patrones de comisiones de varias cuentas
      </Card>
    </CardGroup>
  </Tab>

  <Tab title="Specialized Scenarios">
    **Investigación y análisis**: Cuando estudias patrones de comisiones entre diferentes cuentas y programas

    **Operaciones por lotes**: Cuando analizas simultáneamente patrones de comisiones de muchas cuentas

    **Planificación previa**: Para estimar costos antes de crear flujos de trabajo con transacciones complejas

    **Arquitecturas personalizadas**: Cuando las restricciones del sistema impiden serializar transacciones
  </Tab>
</Tabs>

## Inicio rápido

<Steps>
  <Step title="Identify Accounts">
    Determina qué cuentas participarán en tu transacción
  </Step>

  <Step title="Call the API">
    Envía una solicitud con las claves de cuenta y el nivel de prioridad deseado
  </Step>

  <Step title="Apply the Fee">
    Usa la estimación para establecer la comisión de prioridad de tu transacción
  </Step>
</Steps>

### Ejemplo básico

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

## Guía de implementación

### Función principal

Esta es una función reutilizable para obtener estimaciones de comisiones de prioridad:

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

### Ejemplo completo con varios niveles de prioridad

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

## Tipos de cuentas y estrategias

<Tabs>
  <Tab title="Program Accounts">
    Las cuentas de programas con un gran volumen suelen mostrar comisiones de prioridad más altas debido a la competencia.

    ```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>
      **Comportamiento esperado**: Comisiones más altas debido al gran volumen de transacciones y a la competencia.
    </Note>
  </Tab>

  <Tab title="User Wallets">
    Las billeteras de usuarios activos pueden tener diferentes patrones de comisiones según su actividad.

    ```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>
      **Consejo profesional**: Incluye las billeteras del remitente y del destinatario para obtener estimaciones más precisas.
    </Tip>
  </Tab>

  <Tab title="Token Accounts">
    Las cuentas de tokens específicos pueden mostrar patrones diferentes según la popularidad del 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>

## Opciones de configuración avanzada

<AccordionGroup>
  <Accordion title="Empty Slot Evaluation">
    La opción `evaluateEmptySlotAsZero` es especialmente útil para las estimaciones basadas en cuentas:

    ```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>
      Cuando `true` (valor predeterminado), los slots sin transacciones se tratan como si tuvieran comisiones de cero en lugar de excluirse. Esto ofrece estimaciones más equilibradas para cuentas con poca actividad.
    </Note>
  </Accordion>

  <Accordion title="Include Details">
    Solicita información detallada sobre los patrones de comisiones de cada cuenta:

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

    Esto devuelve información adicional sobre cómo se calcularon las comisiones de cada cuenta.
  </Accordion>

  <Accordion title="Custom Lookback Period">
    Ajusta el número de slots analizados para estimar las comisiones:

    ```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>
      **Período retrospectivo más corto**: Datos más recientes y potencialmente volátiles

      **Período retrospectivo más largo**: Contexto histórico más estable
    </Tip>
  </Accordion>
</AccordionGroup>

## Prácticas recomendadas para seleccionar cuentas

<CardGroup cols={1}>
  <Card title="Include Writable Accounts" icon="pen-to-square">
    **Prioridad**: Céntrate en las cuentas que se modificarán

    ```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">
    **Contexto**: Incluye las cuentas de programas relevantes

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

## Manejo de errores y alternativas

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

## Limitaciones y consideraciones

<Warning>
  **Limitaciones del método basado en cuentas:**

  1. **Menor precisión para cuentas de solo lectura** - El algoritmo se centra en las cuentas con permisos de escritura
  2. **Sin análisis específico de instrucciones** - No puede considerar operaciones específicas
  3. **Dependencia de la actividad de la cuenta** - Es menos preciso para cuentas inactivas
  4. **No considera el tamaño de la transacción** - No tiene en cuenta la complejidad de la transacción
</Warning>

<Note>
  **Cuándo cambiar a transacciones serializadas:**

  * Aplicaciones de producción que requieren la máxima precisión
  * Transacciones complejas con varias instrucciones
  * Cuando importan los patrones de comisiones específicos de las instrucciones
  * Aplicaciones en las que el rendimiento es crítico
</Note>

## Recursos relacionados

<CardGroup cols={2}>
  <Card title="Serialized Transactions" icon="file-code" href="/docs/es/priority-fee/estimating-fees-using-serialized-transaction">
    Método más preciso que usa la serialización completa de transacciones
  </Card>

  <Card title="API Reference" icon="book" href="/docs/es/api-reference/priority-fee/getpriorityfeeestimate">
    Documentación completa de la API y sus parámetros
  </Card>
</CardGroup>
