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

# Helius SDK를 활용한 Solana 프로그래매틱 스테이킹

> Helius SDK로 매끄러운 Solana 스테이킹 경험 구축. 설정에서부터 인출까지 0% 커미션 검증자 통합 완벽 가이드.

<Info>
  **제로 커미션 검증자**: Helius 검증자와 함께 스테이킹하고 0% 커미션으로 스테이킹 보상을 100% 유지하세요.
</Info>

## 빠른 개요

Helius SDK는 전체 SOL 스테이킹 라이프사이클을 프로그래밍 방식으로 처리하는 간단한 방법을 제공합니다. 스테이킹 인터페이스, 디파이 프로토콜, 자동 스테이킹 전략 구축에 적합합니다.

<CardGroup cols={3}>
  <Card title="생성 및 위임" icon="plus">
    새로운 스테이크 계정을 설정하고 한 번의 트랜잭션으로 검증자에게 위임합니다
  </Card>

  <Card title="모니터링 및 관리" icon="chart-line">
    보상 추적, 상태 확인 및 기존 스테이크 계정 관리
  </Card>

  <Card title="출금 및 상환" icon="money-bill">
    스테이크를 비활성화하고 쿨다운 기간 후 SOL 인출
  </Card>
</CardGroup>

## 설치 및 설정

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

## 스테이킹 기본

<AccordionGroup>
  <Accordion title="Solana 스테이킹 작동 방식">
    **스테이크 계정**: SOL을 잠그고 검증자에게 위임하는 특별한 계정입니다. 각 스테이크 계정은 정확히 하나의 검증자를 가리킵니다.

    **보상**: 검증자는 네트워크를 보호하여 보상을 받습니다. 이 보상은 해당 검증자에게 위임된 모든 스테이크 계정에 분배됩니다.

    **라이프사이클**: 생성 → 위임 → 보상 획득 → 비활성화 → 인출
  </Accordion>

  <Accordion title="Helius 검증자를 선택하는 이유">
    * **0% 커미션**: 스테이킹 보상을 100% 유지
    * **고성능**: 안정적인 블록 생성 및 최소 다운타임
    * **쉬운 통합**: Helius SDK에 최적화된 내장 도우미 제공
  </Accordion>

  <Accordion title="타이밍 및 에포크">
    * **활성화**: 스테이크는 다음 에포크 시작 시 활성화됩니다 (\~2일)
    * **비활성화**: 현재 에포크 끝에서 효력이 발생합니다
    * **쿨다운**: 비활성화된 스테이크는 에포크 종료 후 즉시 인출 가능
  </Accordion>
</AccordionGroup>

## 시작하기

<Tabs>
  <Tab title="빠른 시작">
    SOL을 단 3줄의 코드로 스테이킹하기:

    ```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>
      SDK는 자동으로 임대 계산 및 스테이크 계정 생성을 처리합니다. `1.5` 매개 변수는 스테이킹하려는 SOL의 양입니다.
    </Info>
  </Tab>

  <Tab title="완전한 예제">
    오류 처리 포함 전체 스테이킹 구현:

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

## SDK 메서드 참조

<AccordionGroup>
  <Accordion title="createStakeTransaction(owner, amount)">
    서명되고 전송될 수 있는 완전한 스테이킹 트랜잭션을 생성합니다.

    **매개변수:**

    * `owner` (PublicKey): 스테이크 계정을 소유할 지갑
    * `amount` (number): 스테이킹할 SOL의 양

    **반환 값:**

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

    **예제:**

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

  <Accordion title="getStakeInstructions(owner, amount)">
    스테이킹에 필요한 명령을 반환합니다 (사용자 정의 트랜잭션 빌딩에 유용).

    **반환 값:**

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

    **예제:**

    ```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)">
    지갑에 할당된 Helius 검증자 스테이크 계정을 모두 검색합니다.

    **예제:**

    ```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)">
    스테이크 계정을 비활성화(스테이킹 시작)하는 트랜잭션을 생성합니다.

    **예제:**

    ```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?)">
    비활성화된 스테이크 계정에서 인출 가능한 SOL 양을 확인합니다.

    **매개변수:**

    * `includeRent` (boolean): 임대 면제 금액 포함 여부

    **예제:**

    ```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)">
    비활성화된 스테이크 계정에서 SOL을 인출하는 트랜잭션을 생성합니다.

    **예제:**

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

## 완전한 스테이킹 워크플로우

<Steps>
  <Step title="생성 및 위임">
    ```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="스테이크 모니터링">
    ```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="비활성화 (언스테이킹 시작)">
    ```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="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>

## 고급 패턴

<Tabs>
  <Tab title="브라우저 통합">
    지갑 어댑터를 사용하는 브라우저 애플리케이션용:

    ```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="배치 작업">
    여러 지갑에 대해 효율적으로 스테이킹하기:

    ```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="스마트 트랜잭션">
    더 나은 안정성과 최적화를 위한 스마트 트랜잭션 사용하기:

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

## 중요한 참고 사항

<Warning>
  **에포크 시간**: Solana 에포크는 \~2일입니다. 스테이크는 다음 에포크 시작 시 활성화되고 비활성화는 현재 에포크 끝에 효력이 발생합니다.
</Warning>

<Note>
  **임대 고려 사항**: 스테이크 계정에는 임대 면제 예비금(\~0.00228 SOL)이 필요합니다. 전체 잔액을 인출하면 계정이 닫힙니다.
</Note>

<Tip>
  **하드웨어 지갑**: 사용자는 스테이크 계정을 위한 서명(사전 서명)과 수수료 지불자 서명 두 가지를 요청받을 수 있습니다. UX를 적절히 디자인하세요.
</Tip>

## 빠른 참조

간단한 메서드가 필요하신가요? 여기에 필수 메서드가 있습니다:

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

## 다음 단계

<CardGroup cols={2}>
  <Card title="Helius SDK 문서" icon="code" href="https://github.com/helius-labs/helius-sdk">
    사용 가능한 모든 메서드가 포함된 완전한 SDK 참조
  </Card>

  <Card title="스마트 트랜잭션" icon="bolt" href="/docs/ko/sending-transactions/optimizing-transactions">
    우선 수수료와 재시도 로직으로 트랜잭션 최적화
  </Card>

  <Card title="Discord 참여" icon="discord" href="https://discord.com/invite/6GXdee3gBj">
    개발자 커뮤니티의 도움 받기
  </Card>

  <Card title="검증자 대시보드" icon="chart-bar" href="https://www.validators.app/validators/EKgWgpJY5BtX7TeJfhKbqcJT7gzLKFFtj7cjX1XY6CxA">
    Helius 검증자 성능 및 보상 모니터링
  </Card>
</CardGroup>
