> ## 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残高を調べるための簡単な方法です。残高はlamport単位で返されます（1 SOL = 1,000,000,000 lamports）。

このメソッドは、SOLの残高だけが必要で、他のアカウントの詳細が不要な場合には、より軽量です。

## 主な使用例

* **アカウントのSOL保有量を迅速に確認する:** 主な用途は、アカウント（ウォレット、プログラムなど）がどれだけのSOLを保有しているかを確認することです。

## パラメータ

1. パブリックキー（string, 必須）：クエリを行うアカウントのbase-58エンコードされた公開鍵です。

2. 設定オブジェクト（object, オプション）：次のフィールドを含む設定オブジェクトです。
   * コミットメントレベル（string, オプション）：クエリに使用する[コミットメントレベル](https://www.helius.dev/blog/solana-commitment-levels)を指定します。デフォルトは「max」です。
     * max: ノードはクラスターの過半数によって最大ロックアウトに達したと確認された最新のブロックをクエリします。
     * recent: ノードはクラスターの過半数によって投票された最新のブロックをクエリします。
     * single: ノードは自身の最新のブロックをクエリします。注意: ブロックが完了していない可能性があります。
   * スロット（number, オプション）：リクエストが評価される最小スロットです。

## レスポンス

JSON-RPCレスポンスの"result"フィールドには次のオブジェクトが含まれます。

* コンテナ（object）：
  * スロット（number）：残高が取得されたスロット。
  * RPC APIバージョン（string, オプション）：すべてのノードからは提供されない場合もあります。
* 残高（number）：アカウントの残高（unsigned 64-bit integer）をlamport単位で表示。

アカウントがオンチェーンに存在しない場合、通常、getBalanceは0 lamportsを返します。

## 例：アカウントの残高を取得する

メインネットでSerum Program V3 IDのSOL残高をチェックしてみましょう。このプログラムアカウント自体は家賃免除のためにSOLを保持しています。

**注意:** 以下の例であなたの実際の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は効果的です。
* **存在しないアカウント:** アカウントがオンチェーンに存在しない場合（初期化されていない、またはSOLを保持していない）、getBalanceは0を返します。これにより、SOL残高を気にする場合にアカウントの存在をすばやく確認できます。
* **Lamports と SOL:** 残高はlamports単位で返されるため、SOLに変換するには1,000,000,000で割る必要があります。
* **コミットメントレベル:** コミットメントレベルの選択は、残高の速さと確認の程度に影響を与える可能性があります。UI表示目的では「recent」が良いバランスを提供します。重要な金融取引には「max」が最も高い保証を提供します。[Solana Commitment Levels](https://www.helius.dev/blog/solana-commitment-levels)で詳細情報をご覧ください。
* **複数アカウントのバッチ処理:** getBalanceは単一アカウント用ですが、多くのアカウントの残高が必要な場合、getMultipleAccountsを使用して各アカウントの情報からlamport残高を抽出することにより、個別のgetBalance呼び出しを行うより高性能です。

## 関連メソッド

<CardGroup cols={2}>
  <Card title="getAccountInfo" href="/ja/api-reference/rpc/http/getaccountinfo">
    データ、オーナー、および実行可能ステータスを含む完全なアカウント情報を取得します
  </Card>

  <Card title="getMultipleAccounts" href="/ja/api-reference/rpc/http/getmultipleaccounts">
    単一のリクエストで複数アカウントのバッチ取得
  </Card>
</CardGroup>
