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

# getBalance 사용 방법

> getBalance 사용 사례, 코드 예제, 요청 매개변수, 응답 구조 및 팁을 배웁니다.

[`getBalance`](https://www.helius.dev/docs/api-reference/rpc/http/getbalance) RPC 메서드는 Solana 블록체인에서 어떤 계정의 네이티브 SOL 잔액을 간단하게 확인하는 방법입니다. 이는 lamports 단위로 잔액을 반환합니다 (1 SOL = 1,000,000,000 lamports).

이 메서드는 SOL 잔액만 필요하고 다른 계정 세부 정보가 필요 없을 경우 `getAccountInfo`보다 더 가볍습니다.

## 주요 사용 사례

* **계정의 SOL 보유량 신속 확인:** 주요 용도는 지갑, 프로그램 등 계정이 보유한 SOL 양을 확인하는 것입니다.

## 매개변수

1. `publicKey` (string, required): 쿼리할 계정의 base-58 인코딩된 공개 키입니다.

2. `config` (object, optional): 다음 필드를 포함하는 구성 객체:
   * `commitment` (string, optional): 쿼리에 사용할 [커밋 수준](https://www.helius.dev/blog/solana-commitment-levels)을 지정합니다. 기본값은 `finalized`입니다.
     * `finalized`: 클러스터의 슈퍼다수결에 의해 최대 잠금에 도달한 것으로 확인된 가장 최근 블록을 쿼리합니다.
     * `confirmed`: 클러스터의 슈퍼다수결에 의해 투표된 가장 최근 블록을 쿼리합니다.
     * `processed`: 가장 최근 블록을 쿼리합니다. 블록이 완전하지 않을 수 있습니다.
   * `minContextSlot` (number, optional): 요청이 평가될 수 있는 최소 슬롯입니다.

## 응답

JSON-RPC 응답의 `result` 필드는 다음을 포함하는 객체입니다:

* `context` (object):
  * `slot` (number): 잔액이 조회된 슬롯입니다.
  * `apiVersion` (string, optional): RPC API 버전 (모든 노드에서 제공되지 않을 수 있음).
* `value` (number): 계정의 lamports 단위 잔액 (부호 없는 64비트 정수).

계정이 온체인에 존재하지 않으면 `getBalance`은 보통 `0` lamports 값을 반환합니다.

## 예: 계정의 잔액 가져오기

메인넷에서 Serum Program V3 ID (`9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin`)의 SOL 잔액을 확인해봅시다. 이 프로그램 계정 자체는 임대 면제를 위해 SOL을 보유하고 있습니다.

**참고:** 아래 예제에서 `YOUR_API_KEY`을 실제 Helius API 키로 교체하세요.

<CodeGroup>
  ```bash curl theme={"system"}
  curl https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY -X POST -H "Content-Type: application/json" -d \
  '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getBalance",
    "params": [
      "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"
    ]
  }'
  ```

  ```javascript JavaScript (using @solana/web3.js) theme={"system"}
  const { Connection, PublicKey, LAMPORTS_PER_SOL } = require('@solana/web3.js');

  async function checkBalance() {
    const rpcUrl = 'https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY'; // Replace YOUR_API_KEY
    const connection = new Connection(rpcUrl, 'confirmed');
    const accountPubKey = new PublicKey('9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin');

    try {
      const lamports = await connection.getBalance(accountPubKey);
      const sol = lamports / LAMPORTS_PER_SOL;

      console.log(`Account PubKey: ${accountPubKey.toBase58()}`);
      console.log(`Balance (Lamports): ${lamports}`);
      console.log(`Balance (SOL): ${sol}`);

    } catch (error) {
      console.error('Error fetching balance:', error);
    }
  }

  checkBalance();
  ```

  ```typescript Kit theme={"system"}
  import { address, createSolanaRpc } from "@solana/kit";

  const rpc_url = "https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY";
  const rpc = createSolanaRpc(rpc_url);

  const publicKey = address("83astBRguLMdt2h5U1Tpdq5tjFoJ6noeGwaY3mDLVcri");
  const balance = await rpc.getBalance(publicKey).send();

  console.log("Account Balance:", balance);
  ```

  ```rust Rust theme={"system"}
  use anyhow::Result;
  use solana_client::nonblocking::rpc_client::RpcClient;
  use solana_sdk::{
      commitment_config::CommitmentConfig, native_token::LAMPORTS_PER_SOL, pubkey::Pubkey,
  };
  use std::str::FromStr;

  #[tokio::main]
  async fn main() -> Result<()> {
      let client = RpcClient::new_with_commitment(
          String::from("https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY"),
          CommitmentConfig::confirmed(),
      );

      let pubkey = Pubkey::from_str("83astBRguLMdt2h5U1Tpdq5tjFoJ6noeGwaY3mDLVcri")?;
      let balance = client.get_balance(&pubkey).await?;

      println!("{:#?} SOL", balance / LAMPORTS_PER_SOL);

      Ok(())
  }
  ```
</CodeGroup>

## 개발자 팁

* **SOL 잔액 간단 확인:** 계정의 SOL 잔액만 필요하고 소유자, 데이터 또는 실행 가능 상태와 같은 다른 온체인 데이터를 필요로 하지 않는 경우, `getBalance`은 `getAccountInfo`보다 더 효율적입니다.
* **존재하지 않는 계정:** 계정이 온체인에 존재하지 않는 경우 (초기화되지 않았거나 SOL이 없는 경우) `getBalance`은 `0`을 반환합니다. 계정의 SOL 잔액만 신경 쓸 경우 계정 존재 여부를 빠르게 확인할 수 있습니다.
* **Lamports와 SOL:** 잔액은 lamports로 반환됩니다. SOL로 변환하려면 `LAMPORTS_PER_SOL` (1,000,000,000)로 나누어야 합니다.
* **커밋 수준:** `commitment`의 선택은 잔액을 얻는 속도와 그 잔액의 확인 정도에 영향을 줄 수 있습니다. 대부분의 UI 표시 용도의 경우 `confirmed`이 적당합니다. 중요한 금융 거래의 경우 `finalized`이 가장 높은 보장을 제공합니다. 자세한 정보는 [Solana Commitment Levels](https://www.helius.dev/blog/solana-commitment-levels)를 참조하세요.
* **`getMultipleAccounts`과의 일괄 처리:** `getBalance`은 단일 계정을 대상으로 하지만, 여러 계정의 잔액이 필요한 경우 `getMultipleAccounts`을 사용하여 각 계정의 정보를 통해 lamport 잔액을 추출하는 것이 여러 개의 `getBalance` 호출보다 더 성능이 좋을 수 있습니다.

## 관련 메서드

<CardGroup cols={2}>
  <Card title="getAccountInfo" href="/docs/ko/api-reference/rpc/http/getaccountinfo">
    데이터, 소유자 및 실행 가능 상태를 포함한 전체 계정 정보 가져오기
  </Card>

  <Card title="getMultipleAccounts" href="/docs/ko/api-reference/rpc/http/getmultipleaccounts">
    한 번의 요청으로 여러 계정 일괄 가져오기
  </Card>
</CardGroup>
