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

# Staking programático de Solana con Helius SDK

> Crea experiencias fluidas de staking de Solana con Helius SDK. Guía completa desde la configuración hasta el retiro, con integración de un validador con 0 % de comisión.

<Info>
  **Validador sin comisión**: Haz staking con el validador de Helius y conserva el 100 % de tus recompensas de staking gracias a nuestra tasa de comisión del 0 %.
</Info>

## Descripción general rápida

Helius SDK proporciona métodos sencillos para gestionar mediante programación todo el ciclo de vida del staking de SOL. Es ideal para crear interfaces de staking, protocolos DeFi o estrategias automatizadas de staking.

<CardGroup cols={3}>
  <Card title="Create & Delegate" icon="plus">
    Configura nuevas cuentas de stake y delégalas a validadores en una sola transacción
  </Card>

  <Card title="Monitor & Manage" icon="chart-line">
    Haz seguimiento de las recompensas, consulta el estado y administra las cuentas de stake existentes
  </Card>

  <Card title="Withdraw & Redeem" icon="money-bill">
    Desactiva stakes y retira SOL después de los períodos de enfriamiento
  </Card>
</CardGroup>

## Instalación y configuración

<CodeGroup>
  ```bash npm theme={"system"}
  npm install helius-sdk @solana/web3.js bs58
  ```

  ```bash yarn   theme={"system"}
  yarn add helius-sdk @solana/web3.js bs58
  ```

  ```bash pnpm theme={"system"}
  pnpm add helius-sdk @solana/web3.js bs58
  ```
</CodeGroup>

<CodeGroup>
  ```typescript Setup theme={"system"}
  import { Helius } from 'helius-sdk';
  import { Keypair, Transaction } from '@solana/web3.js';
  import bs58 from 'bs58';

  // Initialize Helius client
  const helius = new Helius('YOUR_API_KEY');

  // Your wallet keypair (load from your secure storage)
  const payer = Keypair.fromSecretKey(/* your secret key */);
  ```
</CodeGroup>

## Conceptos básicos del staking

<AccordionGroup>
  <Accordion title="How Solana Staking Works">
    **Cuenta de stake**: Una cuenta especial que bloquea SOL y lo delega a un validador. Cada cuenta de stake apunta exactamente a un validador.

    **Recompensas**: Los validadores obtienen recompensas por proteger la red. Estas recompensas se distribuyen entre todas las cuentas de stake delegadas a ese validador.

    **Ciclo de vida**: Crear → Delegar → Obtener recompensas → Desactivar → Retirar
  </Accordion>

  <Accordion title="Why Choose Helius Validator">
    * **0 % de comisión**: Conserva el 100 % de tus recompensas de staking
    * **Alto rendimiento**: Producción de bloques confiable y tiempo de inactividad mínimo
    * **Integración sencilla**: Optimizado para Helius SDK con funciones auxiliares integradas
  </Accordion>

  <Accordion title="Timing & Epochs">
    * **Activación**: Los stakes se activan al inicio de la siguiente época (\~2 días)
    * **Desactivación**: Entra en vigor al final de la época actual
    * **Enfriamiento**: Los stakes desactivados pueden retirarse inmediatamente después de que termine la época
  </Accordion>
</AccordionGroup>

## Primeros pasos

<Tabs>
  <Tab title="Quick Start">
    Haz staking de SOL con solo 3 líneas de código:

    ```typescript theme={"system"}
    // 1. Create the staking transaction
    const { serializedTx, stakeAccountPubkey } = 
      await helius.rpc.createStakeTransaction(payer.publicKey, 1.5);

    // 2. Sign and send
    const tx = Transaction.from(bs58.decode(serializedTx));
    tx.partialSign(payer);
    const signature = await helius.connection.sendRawTransaction(tx.serialize());

    console.log(`Staked! Transaction: ${signature}`);
    console.log(`Stake Account: ${stakeAccountPubkey}`);
    ```

    <Info>
      El SDK gestiona automáticamente el cálculo de la renta y la creación de la cuenta de stake. El parámetro `1.5` es la cantidad de SOL que quieres poner en staking.
    </Info>
  </Tab>

  <Tab title="Complete Example">
    Implementación completa de staking con gestión de errores:

    ```typescript theme={"system"}
    async function stakeSOL(amountInSol: number) {
      try {
        // Create staking transaction
        const { serializedTx, stakeAccountPubkey } = 
          await helius.rpc.createStakeTransaction(payer.publicKey, amountInSol);
        
        // Deserialize and sign transaction
        const transaction = Transaction.from(bs58.decode(serializedTx));
        transaction.partialSign(payer);
        
        // Send transaction
        const signature = await helius.connection.sendRawTransaction(
          transaction.serialize(),
          { 
            skipPreflight: false,
            preflightCommitment: 'confirmed'
          }
        );
        
        // Wait for confirmation
        await helius.connection.confirmTransaction(signature, 'confirmed');
        
        return {
          signature,
          stakeAccount: stakeAccountPubkey,
          amount: amountInSol
        };
        
      } catch (error) {
        console.error('Staking failed:', error);
        throw error;
      }
    }

    // Usage
    const result = await stakeSOL(2.5);
    console.log(`Successfully staked ${result.amount} SOL`);
    ```
  </Tab>
</Tabs>

## Referencia de métodos del SDK

<AccordionGroup>
  <Accordion title="createStakeTransaction(owner, amount)">
    Crea una transacción de staking completa que se puede firmar y enviar.

    **Parámetros:**

    * `owner` (PublicKey): La billetera que será propietaria de la cuenta de stake
    * `amount` (number): Cantidad de SOL que se pondrá en staking

    **Devuelve:**

    ```typescript theme={"system"}
    {
      serializedTx: string,        // Base58 encoded transaction
      stakeAccountPubkey: string   // New stake account address
    }
    ```

    **Ejemplo:**

    ```typescript theme={"system"}
    const result = await helius.rpc.createStakeTransaction(
      payer.publicKey, 
      1.5  // 1.5 SOL
    );
    ```
  </Accordion>

  <Accordion title="getStakeInstructions(owner, amount)">
    Devuelve solo las instrucciones para hacer staking (útil para crear transacciones personalizadas).

    **Devuelve:**

    ```typescript theme={"system"}
    {
      instructions: TransactionInstruction[],
      stakeAccount: Keypair
    }
    ```

    **Ejemplo:**

    ```typescript theme={"system"}
    const { instructions } = await helius.rpc.getStakeInstructions(
      payer.publicKey, 
      1.5
    );

    // Use with Smart Transactions
    const signature = await helius.rpc.sendSmartTransaction(
      instructions, 
      [payer]
    );
    ```
  </Accordion>

  <Accordion title="getHeliusStakeAccounts(wallet)">
    Obtiene todas las cuentas de stake de una billetera delegadas al validador de Helius.

    **Ejemplo:**

    ```typescript theme={"system"}
    const accounts = await helius.rpc.getHeliusStakeAccounts(
      payer.publicKey.toBase58()
    );

    accounts.forEach(account => {
      const delegation = account.account.data.parsed.info.stake.delegation;
      console.log(`Account: ${account.pubkey}`);
      console.log(`Stake: ${delegation.stake / LAMPORTS_PER_SOL} SOL`);
    });
    ```
  </Accordion>

  <Accordion title="createUnstakeTransaction(owner, stakeAccount)">
    Crea una transacción para desactivar una cuenta de stake (iniciar la salida del staking).

    **Ejemplo:**

    ```typescript theme={"system"}
    const tx = await helius.rpc.createUnstakeTransaction(
      payer.publicKey,
      stakeAccountPubkey
    );

    const transaction = Transaction.from(bs58.decode(tx));
    transaction.partialSign(payer);
    await helius.connection.sendRawTransaction(transaction.serialize());
    ```
  </Accordion>

  <Accordion title="getWithdrawableAmount(stakeAccount, includeRent?)">
    Consulta cuánto SOL se puede retirar de una cuenta de stake desactivada.

    **Parámetros:**

    * `includeRent` (boolean): Indica si se debe incluir la cantidad exenta de renta

    **Ejemplo:**

    ```typescript theme={"system"}
    const available = await helius.rpc.getWithdrawableAmount(stakeAccountPubkey);
    const total = await helius.rpc.getWithdrawableAmount(stakeAccountPubkey, true);

    console.log(`Available now: ${available / LAMPORTS_PER_SOL} SOL`);
    console.log(`Total balance: ${total / LAMPORTS_PER_SOL} SOL`);
    ```
  </Accordion>

  <Accordion title="createWithdrawTransaction(owner, stakeAccount, destination, amount)">
    Crea una transacción para retirar SOL de una cuenta de stake desactivada.

    **Ejemplo:**

    ```typescript theme={"system"}
    const tx = await helius.rpc.createWithdrawTransaction(
      payer.publicKey,
      stakeAccountPubkey,
      destinationPubkey,
      withdrawAmount  // in lamports
    );
    ```
  </Accordion>
</AccordionGroup>

## Flujo de trabajo completo de staking

<Steps>
  <Step title="Create and Delegate">
    ```typescript theme={"system"}
    // Stake 2 SOL to Helius validator
    const { serializedTx, stakeAccountPubkey } = 
      await helius.rpc.createStakeTransaction(payer.publicKey, 2.0);

    const tx = Transaction.from(bs58.decode(serializedTx));
    tx.partialSign(payer);

    const signature = await helius.connection.sendRawTransaction(tx.serialize());
    console.log(`Stake created: ${stakeAccountPubkey}`);
    ```
  </Step>

  <Step title="Monitor Your Stakes">
    ```typescript theme={"system"}
    // Get all your Helius stake accounts
    const accounts = await helius.rpc.getHeliusStakeAccounts(
      payer.publicKey.toBase58()
    );

    console.log(`You have ${accounts.length} active stake accounts`);

    accounts.forEach((account, index) => {
      const info = account.account.data.parsed.info;
      const delegation = info.stake.delegation;
      
      console.log(`Stake ${index + 1}:`);
      console.log(`  Amount: ${delegation.stake / LAMPORTS_PER_SOL} SOL`);
      console.log(`  Activated: Epoch ${delegation.activationEpoch}`);
      console.log(`  Status: ${info.meta.lockup.unixTimestamp === 0 ? 'Active' : 'Locked'}`);
    });
    ```
  </Step>

  <Step title="Deactivate (Start Unstaking)">
    ```typescript theme={"system"}
    // Begin the unstaking process
    const unstakeTx = await helius.rpc.createUnstakeTransaction(
      payer.publicKey,
      stakeAccountPubkey
    );

    const tx = Transaction.from(bs58.decode(unstakeTx));
    tx.partialSign(payer);

    await helius.connection.sendRawTransaction(tx.serialize());
    console.log('Deactivation started. Will be withdrawable next epoch.');
    ```
  </Step>

  <Step title="Withdraw SOL">
    ```typescript theme={"system"}
    // Check withdrawable amount
    const withdrawable = await helius.rpc.getWithdrawableAmount(
      stakeAccountPubkey, 
      true  // include rent
    );

    if (withdrawable > 0) {
      // Create withdrawal instruction
      const withdrawInstruction = helius.rpc.getWithdrawInstruction(
        payer.publicKey,
        stakeAccountPubkey,
        payer.publicKey,  // withdraw to same wallet
        withdrawable
      );
      
      // Send using Smart Transactions for better reliability
      const signature = await helius.rpc.sendSmartTransaction(
        [withdrawInstruction], 
        [payer]
      );
      
      console.log(`Withdrawn ${withdrawable / LAMPORTS_PER_SOL} SOL`);
    }
    ```
  </Step>
</Steps>

## Patrones avanzados

<Tabs>
  <Tab title="Browser Integration">
    Para aplicaciones de navegador que usan adaptadores de billetera:

    ```typescript theme={"system"}
    // Get instructions instead of full transaction
    const { instructions, stakeAccount } = await helius.rpc.getStakeInstructions(
      wallet.publicKey,
      stakeAmount
    );

    // Let the wallet handle transaction building and signing
    const transaction = new Transaction().add(...instructions);

    // Sign with wallet adapter
    const signature = await wallet.sendTransaction(transaction, connection);

    console.log(`Stake account: ${stakeAccount.publicKey.toBase58()}`);
    ```
  </Tab>

  <Tab title="Batch Operations">
    Haz staking de forma eficiente para varias billeteras:

    ```typescript theme={"system"}
    async function batchStake(wallets: Keypair[], amount: number) {
      const promises = wallets.map(async (wallet) => {
        try {
          const { serializedTx, stakeAccountPubkey } = 
            await helius.rpc.createStakeTransaction(wallet.publicKey, amount);
          
          const tx = Transaction.from(bs58.decode(serializedTx));
          tx.partialSign(wallet);
          
          return helius.connection.sendRawTransaction(tx.serialize());
        } catch (error) {
          console.error(`Failed to stake for ${wallet.publicKey.toBase58()}:`, error);
          return null;
        }
      });
      
      const results = await Promise.allSettled(promises);
      const successful = results.filter(r => r.status === 'fulfilled').length;
      
      console.log(`Successfully staked for ${successful}/${wallets.length} wallets`);
    }
    ```
  </Tab>

  <Tab title="Smart Transactions">
    Usa Smart Transactions para mejorar la confiabilidad y la optimización:

    ```typescript theme={"system"}
    // Get individual instructions
    const { instructions } = await helius.rpc.getStakeInstructions(
      payer.publicKey,
      2.5
    );

    // Send with Smart Transaction features:
    // - Automatic priority fee optimization
    // - Retry logic with backoff
    // - Better error handling
    const signature = await helius.rpc.sendSmartTransaction(
      instructions,
      [payer],
      {
        skipPreflight: false,
        maxRetries: 3
      }
    );

    console.log(`Smart transaction sent: ${signature}`);
    ```
  </Tab>
</Tabs>

## Notas importantes

<Warning>
  **Duración de las épocas**: Las épocas de Solana duran \~2 días. Los stakes se activan al inicio de la siguiente época y la desactivación entra en vigor al final de la época actual.
</Warning>

<Note>
  **Consideraciones sobre la renta**: Las cuentas de stake necesitan reservas exentas de renta (\~0.00228 SOL). Retirar el saldo completo cierra la cuenta.
</Note>

<Tip>
  **Billeteras de hardware**: Los usuarios verán dos solicitudes de firma: una para la cuenta de stake (firmada previamente) y otra para quien paga la comisión. Diseña tu experiencia de usuario en consecuencia.
</Tip>

## Referencia rápida

¿Necesitas un recordatorio rápido? Estos son los métodos esenciales:

```typescript theme={"system"}
// Stake SOL
await helius.rpc.createStakeTransaction(owner, amountInSol);

// Check your stakes  
await helius.rpc.getHeliusStakeAccounts(ownerAddress);

// Start unstaking
await helius.rpc.createUnstakeTransaction(owner, stakeAccount);

// Check withdrawable amount
await helius.rpc.getWithdrawableAmount(stakeAccount, includeRent);

// Withdraw SOL
helius.rpc.getWithdrawInstruction(owner, stakeAccount, destination, amount);
```

## Próximos pasos

<CardGroup cols={2}>
  <Card title="Helius SDK Documentation" icon="code" href="https://github.com/helius-labs/helius-sdk">
    Referencia completa del SDK con todos los métodos disponibles
  </Card>

  <Card title="Smart Transactions" icon="bolt" href="/docs/es/sending-transactions/optimizing-transactions">
    Optimiza tus transacciones con comisiones de prioridad y lógica de reintentos
  </Card>

  <Card title="Join Discord" icon="discord" href="https://discord.com/invite/6GXdee3gBj">
    Obtén ayuda de nuestra comunidad de desarrolladores
  </Card>

  <Card title="Validator Dashboard" icon="chart-bar" href="https://www.validators.app/validators/EKgWgpJY5BtX7TeJfhKbqcJT7gzLKFFtj7cjX1XY6CxA">
    Supervisa el rendimiento y las recompensas del validador de Helius
  </Card>
</CardGroup>
