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

# Test Your Program

> Learn how to test a simple Rust program

***

### Quick Access

If you prefer to dive straight into the code:

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

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

  <Card title="Guide" icon="computer" href="/pages/ephemeral-rollups-ers/how-to-guide/local-development" iconType="duotone">
    Local Development
  </Card>
</CardGroup>

***

## Step-By-Step Guide

Build valid transactions that calls your program instructions for delegation and undelegation.
The complete test for this project can be found in the [Typescript Test Script](https://github.com/magicblock-labs/magicblock-engine-examples/blob/main/rust-counter/tests).

<Steps>
  <Step title={<a href="#1-connection">Import SDK and initialize Connection</a>}>
    Set up connection and accounts
  </Step>

  <Step title={<a href="#2-delegate">Delegate PDA on Base Layer</a>}>
    Test CPI hook to delegate state account on Base Layer

    <Note>
      <p>
        These public validators are supported for development. Make sure to add the
        specific ER validator in your delegation instruction:
      </p>

      **Mainnet**

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

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

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

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

      **Devnet**

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

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

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

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

      **Localnet**

      <ul>
        <li>
          Local ER (localhost:7799):{" "}
          <code>mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev</code>
        </li>
      </ul>
    </Note>
  </Step>

  <Step title={<a href="#3-commit">Commit PDA on ER</a>}>
    Test CPI hook to commit state account on ER
  </Step>

  <Step title={<a href="#4-undelegate">Undelegate PDA on ER</a>}>
    Test CPI hook to undelegate state account on ER
  </Step>
</Steps>

***

## Counter Example

The following software packages may be required, other versions may also be compatible:

| Software   | Version | Installation Guide                                      |
| ---------- | ------- | ------------------------------------------------------- |
| **Solana** | 2.3.13  | [Install Solana](https://docs.anza.xyz/cli/install)     |
| **Rust**   | 1.85.0  | [Install Rust](https://www.rust-lang.org/tools/install) |
| **Node**   | 24.10.0 | [Install Node](https://nodejs.org/en/download/current)  |

### Code Snippets

<Tabs>
  <Tab title="1. Connection">
    ### Import SDK and create Connection

    Import relevant libraries `@magicblock-labs/ephemeral-rollups-sdk` or `@magicblock-labs/ephemeral-rollups-kit`. Initialize connection before testing and sending transactions.

    <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>
      These public RPC endpoints are currently free and supported for development:
      <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 />
      Find out more details{" "}
      <a href="/pages/ephemeral-rollups-ers/how-to-guide/local-development">here</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_account"), 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_account"), userKeypair.publicKey.toBuffer()],
        PROGRAM_ID
      );
      ```
    </CodeGroup>

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

  <Tab title="2. Delegate">
    ### Test `delegation` transaction

    Create a instruction with the right order and attributes of accounts, and the instruction discriminator for `delegation` of your program. Send the transaction with the instruction to Base Layer (Solana) network.

    <Card title="Transaction (Base Layer): Delegate" icon="magnifying-glass" href="https://solscan.io/tx/5jUdf5rsfQsbLYAahS9axrnLnEjdbUqtXUmGfgGuS7QqbYJ4FZHgXTNoT1bxPXp7XQu78r8Ebpp1RT2u9V6qsc1r?cluster=devnet" iconType="duotone">
      Inspect transactions details on 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">
    ### Test `commit` transaction

    Create a instruction with the right order and attributes of accounts, and the instruction discriminator for `commit` of your program. Send the transaction with the instruction to ER network.

    <CardGroup cols={2}>
      <Card title="Transaction (ER): Commit" icon="magnifying-glass" href="https://solscan.io/tx/5GiFGyrnJPkEQbhE8EHVYczoj2RPGe1YSnoq1DzcUHAxpyzMUKtxG2Tc7TLkxtcCHr72ftnvmkAVMfecTaf6TCK8?cluster=custom&customUrl=https://devnet.magicblock.app" iconType="duotone">
        Inspect transaction details on Solana Explorer
      </Card>

      <Card title="Transaction (Base layer): Commit" icon="magnifying-glass" href="https://solscan.io/tx/5fHBADq99LAEBzGoeDXGtN3ut8RBf2s5UhbDM1N6TMTpvADNeYLz8e8vinNWj1VhLhrR7UxFoW7bo2u6pBR3YRjj?cluster=devnet" iconType="duotone">
        Inspect transaction details on 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">
    ### Test `undelegation` transaction

    Create a instruction with the right order and attributes of accounts, and the instruction discriminator for `undelegation` of your program. Send the transaction with the instruction to ER network.

    <CardGroup cols={2}>
      <Card title="Transaction (ER): Undelegate" icon="magnifying-glass" href="https://solscan.io/tx/bMN6AhXrGH93Uc6ALibGgjnE39hcnY57mBhYkZ8TRaKxNRvyFaweaQPBmDxPv81cgR47WTTzzhfziTUEgAT8Y5m?cluster=custom&customUrl=https://devnet.magicblock.app" iconType="duotone">
        Inspect transaction details on Solana Explorer
      </Card>

      <Card title="Transaction (Base layer): Undelegate" icon="magnifying-glass" href="https://solscan.io/tx/8JafYWiXmd4CHc2E97WKYnaNPmChZeg8aGYY7UUWaQ7Z54N5WoMcAVivyv2vdn9wKirMkR3y4UcmFPdXYqBtKAa?cluster=devnet" iconType="duotone">
        Inspect transaction details on 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 Explorer

Get insights about your transactions and accounts on Solana:

<CardGroup cols={2}>
  <Card title="Solana Explorer" icon="search" href="https://explorer.solana.com/" iconType="duotone">
    Official Solana Explorer
  </Card>

  <Card title="Solscan" icon="searchengin" href="https://solscan.io/" iconType="duotone">
    Explore Solana Blockchain
  </Card>
</CardGroup>

## Solana RPC Providers

Send transactions and requests through existing RPC providers:

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

Find real-time updates on Solana's validator infrastructure:

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

## Server Status

Subscribe to Solana's and MagicBlock's server status:

<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="/pages/overview/additional-information/system-status" iconType="duotone">
    Subscribe to MagicBlock Server Status
  </Card>
</CardGroup>

***
