> ## 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 Solana com Helius SDK

> Construa experiências de staking Solana perfeitas com o Helius SDK. Guia completo desde a configuração até o saque, com integração de validador de comissão 0%.

<Info>
  **Validador de Comissão Zero**: Firme com o validador Helius e mantenha 100% de suas recompensas de staking com nossa taxa de comissão de 0%.
</Info>

## Visão Geral Rápida

O Helius SDK fornece métodos simples para lidar com todo o ciclo de vida do staking SOL programaticamente. Perfeito para construir interfaces de staking, protocolos DeFi ou estratégias automatizadas de staking.

<CardGroup cols={3}>
  <Card title="Criar & Delegar" icon="plus">
    Configure novas contas de staking e delegue para validadores em uma transação
  </Card>

  <Card title="Monitorar & Gerenciar" icon="chart-line">
    Acompanhe recompensas, verifique o status e gerencie contas de staking existentes
  </Card>

  <Card title="Sacar & Resgatar" icon="money-bill">
    Desative stakes e saque SOL após períodos de espera
  </Card>
</CardGroup>

## Instalação & Configuração

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

## Noções Básicas de Staking

<AccordionGroup>
  <Accordion title="Como Funciona o Staking Solana">
    **Conta de Stake**: Uma conta especial que bloqueia SOL e o delega a um validador. Cada conta de stake aponta para exatamente um validador.

    **Recompensas**: Validadores ganham recompensas por proteger a rede. Essas recompensas são distribuídas a todas as contas de stake delegadas a esse validador.

    **Ciclo de Vida**: Criar → Delegar → Ganhar Recompensas → Desativar → Sacar
  </Accordion>

  <Accordion title="Por Que Escolher o Validador Helius">
    * **0% de Comissão**: Mantenha 100% de suas recompensas de staking
    * **Alto Desempenho**: Produção de blocos confiável e tempo de inatividade mínimo
    * **Integração Fácil**: Otimizado para o Helius SDK com auxiliares integrados
  </Accordion>

  <Accordion title="Tempo & Épocas">
    * **Ativação**: Stakes se tornam ativos no início da próxima época (\~2 dias)
    * **Desativação**: Entra em vigor no final da época atual
    * **Espera**: Stakes desativados podem ser sacados imediatamente após o final da época
  </Accordion>
</AccordionGroup>

## Primeiros Passos

<Tabs>
  <Tab title="Início Rápido">
    Stake SOL em apenas 3 linhas 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>
      O SDK lida automaticamente com o cálculo de aluguel e criação de contas de stake. O parâmetro `1.5` é a quantia em SOL que você deseja apostar.
    </Info>
  </Tab>

  <Tab title="Exemplo Completo">
    Implementação completa de staking com tratamento de erros:

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

## Referência de Métodos do SDK

<AccordionGroup>
  <Accordion title="createStakeTransaction(owner, amount)">
    Cria uma transação de staking completa que pode ser assinada e enviada.

    **Parâmetros:**

    * `owner` (PublicKey): A carteira que será proprietária da conta de stake
    * `amount` (number): Quantia de SOL a ser apostada

    **Retorna:**

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

    **Exemplo:**

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

  <Accordion title="getStakeInstructions(owner, amount)">
    Retorna apenas as instruções para staking (útil para construção de transações personalizadas).

    **Retorna:**

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

    **Exemplo:**

    ```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)">
    Recupera todas as contas de stake delegadas ao validador Helius para uma carteira.

    **Exemplo:**

    ```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)">
    Cria uma transação para desativar (iniciar desinvestimento) uma conta de stake.

    **Exemplo:**

    ```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?)">
    Verifique quanto SOL pode ser sacado de uma conta de stake desativada.

    **Parâmetros:**

    * `includeRent` (boolean): Se deve incluir o valor isento de aluguel

    **Exemplo:**

    ```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)">
    Cria uma transação para sacar SOL de uma conta de stake desativada.

    **Exemplo:**

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

## Fluxo Completo de Staking

<Steps>
  <Step title="Criar e Delegar">
    ```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="Monitore Seus 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="Desativar (Iniciar Desinvestimento)">
    ```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="Sacar 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>

## Padrões Avançados

<Tabs>
  <Tab title="Integração com Navegador">
    Para aplicativos de navegador usando adaptadores de carteira:

    ```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="Operações em Lote">
    Aposte para várias carteiras de forma eficiente:

    ```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="Transações Inteligentes">
    Use Transações Inteligentes para melhor confiabilidade e otimização:

    ```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>
  **Tempo de Época**: As épocas de Solana duram \~2 dias. Stakes são ativados no início da próxima época, e a desativação entra em vigor no final da época atual.
</Warning>

<Note>
  **Considerações de Aluguel**: Contas de stake precisam de reservas isentas de aluguel (\~0.00228 SOL). Sacar o saldo total fecha a conta.
</Note>

<Tip>
  **Carteiras de Hardware**: Os usuários verão dois prompts de assinatura - um para a conta de stake (pré-assinada) e outro para o pagador da taxa. Projetem sua UX de acordo.
</Tip>

## Referência Rápida

Precisa de um lembrete rápido? Aqui estão os métodos essenciais:

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

<CardGroup cols={2}>
  <Card title="Documentação do Helius SDK" icon="code" href="https://github.com/helius-labs/helius-sdk">
    Referência completa do SDK com todos os métodos disponíveis
  </Card>

  <Card title="Transações Inteligentes" icon="bolt" href="/docs/pt-BR/sending-transactions/optimizing-transactions">
    Otimize suas transações com taxas prioritárias e lógica de reexecução
  </Card>

  <Card title="Junte-se ao Discord" icon="discord" href="https://discord.com/invite/6GXdee3gBj">
    Obtenha ajuda da nossa comunidade de desenvolvedores
  </Card>

  <Card title="Painel do Validador" icon="chart-bar" href="https://www.validators.app/validators/EKgWgpJY5BtX7TeJfhKbqcJT7gzLKFFtj7cjX1XY6CxA">
    Monitore o desempenho e as recompensas do validador Helius
  </Card>
</CardGroup>
