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

# 最初のSolanaプログラムをデプロイする

> Solanaプログラムをソースからライブのdevnetトランザクションにするまで、資金調達、デプロイ、コールをすべてHelius RPC経由で行います。

export const DevnetFaucet = () => {
  const [apiKey, setApiKey] = useState('');
  const [address, setAddress] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const handleAirdrop = async e => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setResult(null);
    try {
      const res = await fetch(`https://devnet.helius-rpc.com/?api-key=${apiKey}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: 'faucet',
          method: 'requestAirdrop',
          params: [address, 1000000000]
        })
      });
      const json = await res.json();
      if (json.error) throw new Error(json.error.message || 'Airdrop failed');
      setResult(json.result);
    } catch (err) {
      setError(err.message || 'Airdrop failed. The devnet faucet is rate-limited, try again shortly.');
    } finally {
      setLoading(false);
    }
  };
  const btnClass = loading ? 'px-4 py-2 font-medium rounded-full bg-gray-300 dark:bg-gray-700 cursor-not-allowed' : 'px-4 py-2 font-medium rounded-full bg-primary hover:bg-primary/80 text-white';
  return <div className="p-4 border dark:border-zinc-950/80 rounded-xl bg-white dark:bg-zinc-950/80 shadow-sm">
      <form onSubmit={handleAirdrop} className="space-y-4">
        <div>
          <label className="block text-sm text-zinc-950/70 dark:text-white/70 mb-1">Your API Key</label>
          <input type="text" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Enter your API key" className="w-full p-2 border rounded dark:bg-zinc-900 dark:border-zinc-700" required />
        </div>
        <div>
          <label className="block text-sm text-zinc-950/70 dark:text-white/70 mb-1">Devnet Wallet Address</label>
          <input type="text" value={address} onChange={e => setAddress(e.target.value)} placeholder="Your devnet address" className="w-full p-2 border rounded dark:bg-zinc-900 dark:border-zinc-700" required />
        </div>
        <button type="submit" disabled={loading} className={btnClass}>
          {loading ? 'Requesting...' : 'Request 1 Devnet SOL'}
        </button>
      </form>
      <p className="mt-3 text-xs text-zinc-500 dark:text-zinc-400">
        Your API key is used only in your browser to call Helius directly. It is never sent anywhere else.
      </p>
      {error ? <div className="mt-4 p-3 bg-red-100 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded text-red-700 dark:text-red-300">
          <strong>Error:</strong> {error}
        </div> : null}
      {result ? <div className="mt-4 p-3 bg-green-100 dark:bg-green-900/30 border border-green-200 dark:border-green-800 rounded text-green-700 dark:text-green-300 text-sm break-all">
          <strong>Airdrop sent!</strong> Signature: {result}
        </div> : null}
    </div>;
};

このガイドでは、実際のプログラムをdevnetにデプロイして呼び出し、その全体の流れをHeliusインフラストラクチャ上で実行します。ウォレットに[`requestAirdrop`](/ja/api-reference/rpc/http/requestairdrop)で資金を提供し、事前に作成されたサンプルプログラムをデプロイし、[`sendTransaction`](/ja/api-reference/rpc/http/sendtransaction)で呼び出して、[`getSignatureStatuses`](/ja/api-reference/rpc/http/getsignaturestatuses)で結果を確認します。既製のプログラムを使うことで、Rustを書く代わりにデプロイと呼び出しループに集中できます。

<Info>
  **前提条件:** [Solana CLI](https://solana.com/docs/intro/installation) と [Rust](https://www.rust-lang.org/tools/install)（プログラムをビルドするため）、Node.js 18+（呼び出すため）、および[Helius APIキー](https://dashboard.helius.dev/api-keys)。DevnetはすべてのHeliusプランで動作します。
</Info>

***

<Steps>
  <Step title="Solana CLIをHelius devnet RPCに向ける">
    すべてのCLIコマンドに対してHeliusエンドポイントを使用し、ウォレットがない場合は作成します。

    ```bash theme={"system"}
    solana config set --url https://devnet.helius-rpc.com/?api-key=YOUR_API_KEY
    solana-keygen new --no-bip39-passphrase   # skip if you already have a keypair
    solana address
    ```

    `solana address`はあなたのウォレットの公開鍵を表示します。この次に資金提供します。
  </Step>

  <Step title="Devnet SOLを取得する">
    デプロイにはわずかなSOLが必要です。Devnet SOLは無料でテストにのみ使用されるため、以下のファウセットまたはCLIからアドレスに資金提供します。

    ```bash theme={"system"}
    solana airdrop 1
    solana balance
    ```

    <DevnetFaucet />

    <Note>
      Devnetファウセットはレート制限されているため、エアドロップが失敗する場合があります。失敗した場合、少し待って再試行するか、公式のSolana [devnet web faucet](https://faucet.solana.com/)を代替手段として使用してください。サンプルプログラムのデプロイには約1 SOLだけが必要です。
    </Note>
  </Step>

  <Step title="サンプルプログラムをクローンしてビルドする">
    Solanaの公式[program-examples](https://github.com/solana-developers/program-examples)リポジトリから「Hello, Solana!」プログラムを取得します。それは呼び出されると挨拶をログに記録するもので、このような小さなプログラムでも完全なループが機能することを証明します。

    ```bash theme={"system"}
    git clone https://github.com/solana-developers/program-examples.git
    cd program-examples
    cargo build-sbf --manifest-path basics/hello-solana/native/program/Cargo.toml
    ```

    `program-examples`はCargoワークスペースであるため、`cargo build-sbf`はプログラムをリポジトリのルート（プログラムフォルダの内部ではなく）にコンパイルします。次のステップのために`program-examples`ディレクトリに留まります。
  </Step>

  <Step title="Heliusを介してdevnetにデプロイする">
    ```bash theme={"system"}
    solana program deploy target/deploy/hello_solana_program.so
    ```

    CLIはHelius RPCを通じてデプロイトランザクションを送信し、**プログラムID**を表示します。これをコピーしてください。このプログラムを次に呼び出します。

    ```
    Program Id: 4Nd1mYQ...your program id...
    ```
  </Step>

  <Step title="sendTransactionでプログラムを呼び出す">
    新しいフォルダーでトランザクションを構築し、送信し、確認する小さなTypeScriptクライアントを設定します。

    ```bash theme={"system"}
    mkdir invoke-client && cd invoke-client
    npm init -y
    npm install @solana/web3.js
    ```

    ```typescript invoke.ts [expandable] theme={"system"}
    import {
      Connection,
      Keypair,
      PublicKey,
      Transaction,
      TransactionInstruction,
    } from "@solana/web3.js";
    import { readFileSync } from "fs";
    import { homedir } from "os";

    const RPC = "https://devnet.helius-rpc.com/?api-key=YOUR_API_KEY";
    const PROGRAM_ID = new PublicKey("YOUR_PROGRAM_ID"); // from the deploy step

    async function main() {
      const connection = new Connection(RPC, "confirmed");

      // Load the same keypair the CLI created and funded.
      const secret = JSON.parse(
        readFileSync(`${homedir()}/.config/solana/id.json`, "utf8")
      );
      const payer = Keypair.fromSecretKey(Uint8Array.from(secret));

      // The hello-solana program takes no accounts and no data. It just logs.
      const instruction = new TransactionInstruction({
        keys: [],
        programId: PROGRAM_ID,
        data: Buffer.alloc(0),
      });

      const tx = new Transaction().add(instruction);
      const { blockhash } = await connection.getLatestBlockhash();
      tx.recentBlockhash = blockhash;
      tx.feePayer = payer.publicKey;
      tx.sign(payer);

      // sendTransaction submits the signed transaction to the cluster via Helius.
      const signature = await connection.sendRawTransaction(tx.serialize());
      console.log("Sent:", signature);

      // Poll getSignatureStatuses until the transaction is confirmed.
      for (let i = 0; i < 30; i++) {
        const { value } = await connection.getSignatureStatuses([signature]);
        const status = value[0];
        if (status?.confirmationStatus === "confirmed" || status?.confirmationStatus === "finalized") {
          if (status.err) throw new Error(`Failed: ${JSON.stringify(status.err)}`);
          console.log("Confirmed! View it on Solana Explorer:");
          console.log(`https://explorer.solana.com/tx/${signature}?cluster=devnet`);
          return;
        }
        await new Promise((r) => setTimeout(r, 1000));
      }
      throw new Error("Timed out waiting for confirmation");
    }

    main().catch(console.error);
    ```

    `YOUR_API_KEY`と`YOUR_PROGRAM_ID`を置き換えて、実行します。

    ```bash theme={"system"}
    npx tsx invoke.ts
    ```

    署名とExplorerリンクが得られます。リンクを開き、**プログラム命令ログ**を展開して、プログラムの`Hello, Solana!`挨拶を見てください。
  </Step>
</Steps>

## 何が起こっているのか

### すべてがHelius RPCを通じてルートされる

`solana config set --url`はすべてのCLIコマンド（エアドロップ、デプロイ、残高チェック）をHelius devnetエンドポイントに向けます。TypeScriptクライアントも同じエンドポイントを使用するため、全体のフローがHeliusインフラストラクチャ上で実行されます。

### 呼び出しループ: 送信し、次に確認

`sendRawTransaction`は内部で[`sendTransaction`](/ja/api-reference/rpc/http/sendtransaction) RPCメソッドを呼び出し、ネットワークがトランザクションを処理する前に署名をすぐに返します。そのため、[`getSignatureStatuses`](/ja/api-reference/rpc/http/getsignaturestatuses)をポーリングして`confirmationStatus`が`confirmed`に達するまで確認し、`err`で失敗をキャッチします。この送信して確認するパターンは、送信されるすべてのSolanaトランザクションの基本です。

## 次のステップ

<CardGroup cols={2}>
  <Card title="Devnet SOLの取得方法" icon="faucet-drip" href="/ja/rpc/devnet-sol">
    Devnetウォレットに資金を提供するすべての方法、レート制限のヒント付き。
  </Card>

  <Card title="sendTransaction" icon="paper-plane" href="/ja/api-reference/rpc/http/sendtransaction">
    skipPreflight、preflightCommitment、再試行を含むすべてのパラメーター。
  </Card>

  <Card title="トランザクションを信頼性高く着地させる" icon="rocket" href="/ja/api-reference/sender/sendtransaction">
    Mainnetに行くときは、Senderを使用して超低遅延ランディング。
  </Card>

  <Card title="ポートフォリオトラッカーを構築する" icon="wallet" href="/ja/quickstart/portfolio-tracker">
    他のトラック: 任意のウォレットのトークン、NFT、SOLをプルし、ライブ活動フィードを提供。
  </Card>
</CardGroup>
