> ## Documentation Index
> Fetch the complete documentation index at: https://docs.magicblock.gg/llms.txt
> Use this file to discover all available pages before exploring further.

# プログラムをテストする

> シンプルな Rust プログラムのテスト方法を学ぶ

***

### クイックアクセス

すぐにコードを見たい場合はこちらです。

<CardGroup cols={2}>
  <Card title="GitHub" icon="js" href="https://github.com/magicblock-labs/magicblock-engine-examples/blob/main/rust-counter/tests" iconType="duotone">
    Rust Counter のテスト
  </Card>

  <Card title="GitHub" icon="js" href="https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/pinocchio-counter/tests" iconType="duotone">
    Pinocchio Counter のテスト
  </Card>

  <Card title="Guide" icon="computer" href="/jp/pages/ephemeral-rollups-ers/how-to-guide/local-development" iconType="duotone">
    ローカル開発
  </Card>
</CardGroup>

***

## ステップバイステップガイド

delegation と undelegation 用 instruction を呼び出す有効なトランザクションを組み立てます。
このプロジェクトの完全なテストは [Typescript Test Script](https://github.com/magicblock-labs/magicblock-engine-examples/blob/main/rust-counter/tests) にあります。

<Steps>
  <Step title={<a href="#1-connection">SDK をインポートし Connection を初期化する</a>}>
    connection とアカウントをセットアップする
  </Step>

  <Step title={<a href="#2-delegate">Base Layer で PDA を Delegate する</a>}>
    Base Layer 上で状態アカウントを委任する CPI hook をテストする

    <Note>
      <p>
        これらの公開バリデータは開発用として利用できます。委任命令には、
        対象となる ER バリデータを必ず追加してください。
      </p>

      **メインネット**

      <ul>
        <li>
          アジア (as.magicblock.app):{" "}
          <code>MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57</code>
        </li>

        <li>
          EU (eu.magicblock.app):{" "}
          <code>MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e</code>
        </li>

        <li>
          米国 (us.magicblock.app):{" "}
          <code>MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd</code>
        </li>

        <li>
          TEE (mainnet-tee.magicblock.app):{" "}
          <code>MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo</code>
        </li>
      </ul>

      **Devnet**

      <ul>
        <li>
          アジア (devnet-as.magicblock.app):{" "}
          <code>MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57</code>
        </li>

        <li>
          EU (devnet-eu.magicblock.app):{" "}
          <code>MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e</code>
        </li>

        <li>
          米国 (devnet-us.magicblock.app):{" "}
          <code>MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd</code>
        </li>

        <li>
          TEE (devnet-tee.magicblock.app):{" "}
          <code>MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo</code>
        </li>
      </ul>

      **ローカルネット**

      <ul>
        <li>
          ローカル ER (localhost:7799):{" "}
          <code>mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev</code>
        </li>
      </ul>
    </Note>
  </Step>

  <Step title={<a href="#3-commit">ER で PDA を Commit する</a>}>
    ER 上で状態アカウントをコミットする CPI hook をテストする
  </Step>

  <Step title={<a href="#4-undelegate">ER で PDA を Undelegate する</a>}>
    ER 上で状態アカウントを委任解除する CPI hook をテストする
  </Step>
</Steps>

***

## Counter 例

以下のソフトウェアパッケージが必要になる場合があります。ほかのバージョンでも互換性がある可能性があります。

| ソフトウェア     | バージョン   | インストールガイド                                               |
| ---------- | ------- | ------------------------------------------------------- |
| **Solana** | 3.1.9   | [Solana をインストール](https://docs.anza.xyz/cli/install)     |
| **Rust**   | 1.89.0  | [Rust をインストール](https://www.rust-lang.org/tools/install) |
| **Node**   | 24.10.0 | [Node をインストール](https://nodejs.org/en/download/current)  |

<div id="code-snippets" />

### コードスニペット

<Tabs>
  <Tab title="1. Connection">
    ### SDK をインポートして Connection を作成する

    `@magicblock-labs/ephemeral-rollups-sdk` または `@magicblock-labs/ephemeral-rollups-kit` をインポートし、テストやトランザクション送信の前に connection を初期化します。

    <CodeGroup>
      ```bash kit theme={null}
      yarn add @magicblock-labs/ephemeral-rollups-kit@latest
      ```

      ```bash web3.js theme={null}
      yarn add @magicblock-labs/ephemeral-rollups-sdk@latest
      ```
    </CodeGroup>

    <Note>
      これらの公開 RPC エンドポイントは現在無料で、開発用途に利用できます:
      <br /> Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) <br />
      Solana Devnet: [https://api.devnet.solana.com](https://api.devnet.solana.com) <br />
      ER Devnet: [https://devnet.magicblock.app](https://devnet.magicblock.app) <br />
      TEE Devnet: [https://devnet-tee.magicblock.app/](https://devnet-tee.magicblock.app/) <br />
      詳細は{" "}
      <a href="/jp/pages/ephemeral-rollups-ers/how-to-guide/local-development">こちら</a>
      をご覧ください。
    </Note>

    <CodeGroup>
      ```typescript Kit theme={null}
      import {
        Instruction,
        getAddressEncoder,
        getProgramDerivedAddress,
        AccountRole,
        createKeyPairFromBytes,
        getAddressFromPublicKey,
        address,
        createTransactionMessage,
        appendTransactionMessageInstructions,
        pipe,
        setTransactionMessageFeePayer,
      } from "@solana/kit";

      import {
        Connection,
        DELEGATION_PROGRAM_ID,
        delegationRecordPdaFromDelegatedAccount,
        delegationMetadataPdaFromDelegatedAccount,
        delegateBufferPdaFromDelegatedAccountAndOwnerProgram,
        MAGIC_CONTEXT_ID,
        MAGIC_PROGRAM_ID,
      } from "@magicblock-labs/ephemeral-rollups-kit";

      // Set up a base and ephemeral connection (alternatively use router, see Magic Router)
      const connection = await Connection.create(
        process.env.PROVIDER_ENDPOINT || "https://api.devnet.solana.com",
        process.env.WS_ENDPOINT || "wss://api.devnet.solana.com"
      );
      const ephemeralConnection = await Connection.create(
        process.env.EPHEMERAL_PROVIDER_ENDPOINT || "https://devnet-as.magicblock.app",
        process.env.EPHEMERAL_WS_ENDPOINT || "wss://devnet-as.magicblock.app"
      );

      // Prepare user
      const userKeypair = await initializeSolSignerKeypair();
      const userPubkey = await getAddressFromPublicKey(userKeypair.publicKey);

      // Get PDA
      const addressEncoder = getAddressEncoder();
      const [counterPda, bump] = await getProgramDerivedAddress({
        programAddress: PROGRAM_ID,
        seeds: [Buffer.from("counter"), addressEncoder.encode(userPubkey)],
      });
      ```

      ```typescript Web3.js theme={null}
      import {
        Keypair,
        PublicKey,
        SystemProgram,
        Transaction,
        TransactionInstruction,
        Connection,
        sendAndConfirmTransaction,
      } from "@solana/web3.js";

      import {
        DELEGATION_PROGRAM_ID,
        delegationRecordPdaFromDelegatedAccount,
        delegationMetadataPdaFromDelegatedAccount,
        delegateBufferPdaFromDelegatedAccountAndOwnerProgram,
        MAGIC_CONTEXT_ID,
        MAGIC_PROGRAM_ID,
        GetCommitmentSignature,
      } from "@magicblock-labs/ephemeral-rollups-sdk";

      // Set up a base and ephemeral connection (alternatively use router, see Magic Router)
      const connectionBaseLayer = new Connection(
        process.env.PROVIDER_ENDPOINT || "https://api.devnet.solana.com",
        { wsEndpoint: process.env.WS_ENDPOINT || "wss://api.devnet.solana.com" }
      );
      const connectionEphemeralRollup = new Connection(
        process.env.EPHEMERAL_PROVIDER_ENDPOINT ||
          "https://devnet-as.magicblock.app/",
        {
          wsEndpoint:
            process.env.EPHEMERAL_WS_ENDPOINT || "wss://devnet-as.magicblock.app/",
        }
      );

      // Create user keypair and airdrop SOL if needed
      const userKeypair = initializeSolSignerKeypair();

      // Get pda
      let [counterPda, bump] = PublicKey.findProgramAddressSync(
        [Buffer.from("counter"), userKeypair.publicKey.toBuffer()],
        PROGRAM_ID
      );
      ```
    </CodeGroup>

    [⬆️ Back to Top](#code-snippets)
  </Tab>

  <Tab title="2. Delegate">
    ### `delegation` トランザクションをテストする

    アカウントの順序と属性が正しく、かつプログラムの `delegation` 用 instruction discriminator を持つ instruction を作成します。その instruction を含むトランザクションを Base Layer（Solana）ネットワークへ送信します。

    <Card title="トランザクション（Base Layer）: Delegate" icon="magnifying-glass" href="https://solscan.io/tx/5jUdf5rsfQsbLYAahS9axrnLnEjdbUqtXUmGfgGuS7QqbYJ4FZHgXTNoT1bxPXp7XQu78r8Ebpp1RT2u9V6qsc1r?cluster=devnet" iconType="duotone">
      Solana Explorer でトランザクション詳細を見る
    </Card>

    <CodeGroup>
      ```typescript Kit theme={null}
      // "Delegate" transaction

      // Add local validator identity to the remaining accounts if running on localnet
      const remainingAccounts =
        connection.clusterUrlHttp.includes("localhost") ||
        connection.clusterUrlHttp.includes("127.0.0.1")
          ? [
              {
                address: address("mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev"),
                role: AccountRole.READONLY,
              },
            ]
          : [];
      const accounts = [
        { address: userPubkey, role: AccountRole.WRITABLE_SIGNER },
        { address: SYSTEM_PROGRAM_ADDRESS, role: AccountRole.READONLY },
        { address: counterPda, role: AccountRole.WRITABLE },
        { address: PROGRAM_ID, role: AccountRole.READONLY },
        {
          address: await delegateBufferPdaFromDelegatedAccountAndOwnerProgram(
            counterPda,
            PROGRAM_ID
          ),
          role: AccountRole.WRITABLE,
        },
        {
          address: await delegationRecordPdaFromDelegatedAccount(counterPda),
          role: AccountRole.WRITABLE,
        },
        {
          address: await delegationMetadataPdaFromDelegatedAccount(counterPda),
          role: AccountRole.WRITABLE,
        },
        { address: DELEGATION_PROGRAM_ID, role: AccountRole.READONLY },
        ...remainingAccounts,
      ];
      const serializedInstructionData = Buffer.from(
        CounterInstruction.Delegate,
        "hex"
      );
      const delegateIx: Instruction = {
        accounts,
        programAddress: PROGRAM_ID,
        data: serializedInstructionData,
      };
      const transactionMessage = pipe(
        createTransactionMessage({ version: 0 }),
        (tx) => setTransactionMessageFeePayer(userPubkey, tx),
        (tx) => appendTransactionMessageInstructions([delegateIx], tx)
      );

      // Send and confirm transaction on base layer
      const txHash = await connection.sendAndConfirmTransaction(
        transactionMessage,
        [userKeypair],
        { commitment: "confirmed", skipPreflight: true }
      );
      ```

      ```typescript Web3.js theme={null}
      // "Delegate" transaction

      // Add local validator identity to the remaining accounts if running on localnet
      const remainingAccounts =
        connectionEphemeralRollup.rpcEndpoint.includes("localhost") ||
        connectionEphemeralRollup.rpcEndpoint.includes("127.0.0.1")
          ? [
              {
                pubkey: new PublicKey("mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev"),
                isSigner: false,
                isWritable: false,
              },
            ]
          : [];

      const tx = new web3.Transaction();
      const keys = [
        // Initializer
        {
          pubkey: userKeypair.publicKey,
          isSigner: true,
          isWritable: true,
        },
        // System Program
        {
          pubkey: web3.SystemProgram.programId,
          isSigner: false,
          isWritable: false,
        },
        // Counter Account
        {
          pubkey: counterPda,
          isSigner: false,
          isWritable: true,
        },
        // Owner Program
        {
          pubkey: PROGRAM_ID,
          isSigner: false,
          isWritable: false,
        },
        // Delegation Buffer
        {
          pubkey: getDelegationBufferPda(counterPda, PROGRAM_ID),
          isSigner: false,
          isWritable: true,
        },
        // Delegation Record
        {
          pubkey: getDelegationRecordPda(counterPda),
          isSigner: false,
          isWritable: true,
        },
        // Delegation Metadata
        {
          pubkey: getDelegationMetadataPda(counterPda),
          isSigner: false,
          isWritable: true,
        },
        // Delegation Program
        {
          pubkey: DELEGATION_PROGRAM_ID,
          isSigner: false,
          isWritable: false,
        },
        // ER Validator
        ...remainingAccounts,
      ];
      const serializedInstructionData = Buffer.from(
        CounterInstruction.Delegate,
        "hex"
      );
      const delegateIx = new web3.TransactionInstruction({
        keys: keys,
        programId: PROGRAM_ID,
        data: serializedInstructionData,
      });
      tx.add(delegateIx);

      // Send and confirm transaction to Base Layer
      const txHash = await sendAndConfirmTransaction(
        connectionBaseLayer,
        tx,
        [userKeypair],
        {
          skipPreflight: true,
          commitment: "confirmed",
        }
      );
      ```
    </CodeGroup>

    [⬆️ Back to Top](#code-snippets)
  </Tab>

  <Tab title="3. Commit">
    ### `commit` トランザクションをテストする

    アカウントの順序と属性が正しく、かつプログラムの `commit` 用 instruction discriminator を持つ instruction を作成します。その instruction を含むトランザクションを ER ネットワークへ送信します。

    <CardGroup cols={2}>
      <Card title="トランザクション（ER）: Commit" icon="magnifying-glass" href="https://solscan.io/tx/5GiFGyrnJPkEQbhE8EHVYczoj2RPGe1YSnoq1DzcUHAxpyzMUKtxG2Tc7TLkxtcCHr72ftnvmkAVMfecTaf6TCK8?cluster=custom&customUrl=https://devnet.magicblock.app" iconType="duotone">
        Solana Explorer でトランザクション詳細を見る
      </Card>

      <Card title="トランザクション（Base layer）: Commit" icon="magnifying-glass" href="https://solscan.io/tx/5fHBADq99LAEBzGoeDXGtN3ut8RBf2s5UhbDM1N6TMTpvADNeYLz8e8vinNWj1VhLhrR7UxFoW7bo2u6pBR3YRjj?cluster=devnet" iconType="duotone">
        Solana Explorer でトランザクション詳細を見る
      </Card>
    </CardGroup>

    <CodeGroup>
      ```typescript Kit theme={null}
      // "Commit" transaction

      const accounts = [
        { address: userPubkey, role: AccountRole.WRITABLE_SIGNER },
        { address: counterPda, role: AccountRole.WRITABLE },
        { address: address(MAGIC_PROGRAM_ID.toString()), role: AccountRole.READONLY },
        { address: address(MAGIC_CONTEXT_ID.toString()), role: AccountRole.WRITABLE },
      ];
      const serializedInstructionData = Buffer.from(CounterInstruction.Commit, "hex");
      const commitIx: Instruction = {
        accounts,
        programAddress: PROGRAM_ID,
        data: serializedInstructionData,
      };
      const transactionMessage = pipe(
        createTransactionMessage({ version: 0 }),
        (tx) => setTransactionMessageFeePayer(userPubkey, tx),
        (tx) => appendTransactionMessageInstructions([commitIx], tx)
      );

      // Send and confirm transaction on ER
      const txHash = await ephemeralConnection.sendAndConfirmTransaction(
        transactionMessage,
        [userKeypair],
        { commitment: "confirmed", skipPreflight: true }
      );
      ```

      ```typescript Web3.js theme={null}
      // "Commit" transaction

      const tx = new web3.Transaction();
      const keys = [
        // Initializer
        {
          pubkey: userKeypair.publicKey,
          isSigner: true,
          isWritable: true,
        },
        // Counter Account
        {
          pubkey: counterPda,
          isSigner: false,
          isWritable: true,
        },
        // Magic Program
        {
          pubkey: MAGIC_PROGRAM_ID,
          isSigner: false,
          isWritable: false,
        },
        // Magic Context
        {
          pubkey: MAGIC_CONTEXT_ID,
          isSigner: false,
          isWritable: true,
        },
      ];
      const serializedInstructionData = Buffer.from(CounterInstruction.Commit, "hex");
      const commitIx = new web3.TransactionInstruction({
        keys: keys,
        programId: PROGRAM_ID,
        data: serializedInstructionData,
      });
      tx.add(commitIx);

      // Send and confirm transaction to ER
      const txHash = await sendAndConfirmTransaction(
        connectionEphemeralRollup,
        tx,
        [userKeypair],
        {
          skipPreflight: true,
          commitment: "confirmed",
        }
      );
      ```
    </CodeGroup>

    [⬆️ Back to Top](#code-snippets)
  </Tab>

  <Tab title="4. Undelegate">
    ### `undelegation` トランザクションをテストする

    アカウントの順序と属性が正しく、かつプログラムの `undelegation` 用 instruction discriminator を持つ instruction を作成します。その instruction を含むトランザクションを ER ネットワークへ送信します。

    <CardGroup cols={2}>
      <Card title="トランザクション（ER）: Undelegate" icon="magnifying-glass" href="https://solscan.io/tx/bMN6AhXrGH93Uc6ALibGgjnE39hcnY57mBhYkZ8TRaKxNRvyFaweaQPBmDxPv81cgR47WTTzzhfziTUEgAT8Y5m?cluster=custom&customUrl=https://devnet.magicblock.app" iconType="duotone">
        Solana Explorer でトランザクション詳細を見る
      </Card>

      <Card title="トランザクション（Base layer）: Undelegate" icon="magnifying-glass" href="https://solscan.io/tx/8JafYWiXmd4CHc2E97WKYnaNPmChZeg8aGYY7UUWaQ7Z54N5WoMcAVivyv2vdn9wKirMkR3y4UcmFPdXYqBtKAa?cluster=devnet" iconType="duotone">
        Solana Explorer でトランザクション詳細を見る
      </Card>
    </CardGroup>

    <CodeGroup>
      ```typescript Kit theme={null}
      // "Undelegate" transaction

      const accounts = [
        { address: userPubkey, role: AccountRole.WRITABLE_SIGNER },
        { address: counterPda, role: AccountRole.WRITABLE },
        { address: address(MAGIC_PROGRAM_ID.toString()), role: AccountRole.READONLY },
        { address: address(MAGIC_CONTEXT_ID.toString()), role: AccountRole.WRITABLE },
      ];
      const serializedInstructionData = Buffer.from(
        CounterInstruction.CommitAndUndelegate,
        "hex"
      );
      const undelegateIx: Instruction = {
        accounts,
        programAddress: PROGRAM_ID,
        data: serializedInstructionData,
      };
      const transactionMessage = pipe(
        createTransactionMessage({ version: 0 }),
        (tx) => setTransactionMessageFeePayer(userPubkey, tx),
        (tx) => appendTransactionMessageInstructions([undelegateIx], tx)
      );

      // Send and confirm transaction on ER
      const txHash = await ephemeralConnection.sendAndConfirmTransaction(
        transactionMessage,
        [userKeypair],
        { commitment: "confirmed", skipPreflight: true }
      );
      ```

      ```typescript Web3.js theme={null}
      // "Undelegate" transaction

      const tx = new web3.Transaction();
      const keys = [
        // Initializer
        {
          pubkey: userKeypair.publicKey,
          isSigner: true,
          isWritable: true,
        },
        // Counter Account
        {
          pubkey: counterPda,
          isSigner: false,
          isWritable: true,
        },
        // Magic Program
        {
          pubkey: MAGIC_PROGRAM_ID,
          isSigner: false,
          isWritable: false,
        },
        // Magic Context
        {
          pubkey: MAGIC_CONTEXT_ID,
          isSigner: false,
          isWritable: true,
        },
      ];
      const serializedInstructionData = Buffer.from(
        CounterInstruction.CommitAndUndelegate,
        "hex"
      );
      const undelegateIx = new web3.TransactionInstruction({
        keys: keys,
        programId: PROGRAM_ID,
        data: serializedInstructionData,
      });
      tx.add(undelegateIx);

      // Send and confirm transaction to ER. Afterwards CPI callback will be triggered to "Undelegate" instruction of your program on the Base Layer.
      const txHash = await sendAndConfirmTransaction(
        connectionEphemeralRollup,
        tx,
        [userKeypair],
        {
          skipPreflight: true,
          commitment: "confirmed",
        }
      );
      ```
    </CodeGroup>

    [⬆️ Back to Top](#code-snippets)
  </Tab>
</Tabs>

***

## Solana エクスプローラー

Solana 上のトランザクションとアカウントの情報を確認できます。

<CardGroup cols={2}>
  <Card title="Solana エクスプローラー" icon="search" href="https://explorer.solana.com/" iconType="duotone">
    公式 Solana エクスプローラー
  </Card>

  <Card title="Solscan" icon="searchengin" href="https://solscan.io/" iconType="duotone">
    Solana ブロックチェーンを探索する
  </Card>
</CardGroup>

## Solana RPC プロバイダー

既存の RPC プロバイダーを通じてトランザクションやリクエストを送信します。

<CardGroup cols={2}>
  <Card title="Solana" icon="star" href="https://solana.com/docs/references/clusters#on-a-high-level" iconType="duotone">
    Free Public Nodes
  </Card>

  <Card title="Helius" icon="sun" href="https://www.helius.dev/solana-rpc-nodes" iconType="duotone">
    Free Shared Nodes
  </Card>

  <Card title="Triton" icon="crystal-ball" href="https://triton.one/solana" iconType="duotone">
    Dedicated High-Performance Nodes
  </Card>
</CardGroup>

## Solana バリデータダッシュボード

Solana バリデータインフラのリアルタイム更新を確認できます。

<CardGroup cols={2}>
  <Card title="Solana Beach" icon="wave" href="https://solanabeach.io/" iconType="duotone">
    Get Validator Insights
  </Card>

  <Card title="Validators App" icon="cloud-binary" href="https://www.validators.app/" iconType="duotone">
    Discover Validator Metrics
  </Card>
</CardGroup>

## サーバーステータス

Solana と MagicBlock のサーバーステータスを確認しましょう。

<CardGroup cols={2}>
  <Card title="Solana Status" icon="server" href="https://status.solana.com/" iconType="duotone">
    Subscribe to Solana Server Updates
  </Card>

  <Card title="MagicBlock Status" icon="heart-pulse" href="/jp/pages/overview/additional-information/system-status" iconType="duotone">
    Subscribe to MagicBlock Server Status
  </Card>
</CardGroup>

***
