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

> [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/native-rust/tests)
>
> Tests for Rust Counter

> [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/pinocchio/tests)
>
> Tests for Pinocchio Counter

> [card] [Guide](https://docs.magicblock.gg/pages/ephemeral-rollups-ers/how-to-guide/local-development.md)
>
> Local Development

***

## 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/tree/main/counter/native-rust/tests).

**1. [Import SDK and initialize Connection](#1-connection)**

Set up connection and accounts

**2. [Delegate PDA on Base Layer](#2-delegate)**

Test CPI hook to delegate state account on Base Layer

> [!NOTE]
>
> These public validators are supported for development. Make sure to add the
> specific ER validator in your delegation instruction:
>
> **Mainnet**
>
> <ul>
>   <li>
>     Asia (as.magicblock.app):&#x20;
>     `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57`
>   </li>
>
>   <li>
>     EU (eu.magicblock.app):&#x20;
>     `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e`
>   </li>
>
>   <li>
>     US (us.magicblock.app):&#x20;
>     `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd`
>   </li>
>
>   <li>
>     TEE (mainnet-tee.magicblock.app):&#x20;
>     `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo`
>   </li>
>
>   <li>
>     Asia Tokyo (as-tyo.magicblock.app):&#x20;
>     `MSHuBweMkNp4yPLDkPLA8bLRHbDmURWjYzsxrcBjix8`
>   </li>
>
>   <li>
>     South America (sa.magicblock.app):&#x20;
>     `MSARyz2yVTkqiYQWWgaEtUKug7oCF7PphE9GjEYHtDh`
>   </li>
> </ul>
>
> **Devnet**
>
> <ul>
>   <li>
>     Asia (devnet-as.magicblock.app):&#x20;
>     `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57`
>   </li>
>
>   <li>
>     EU (devnet-eu.magicblock.app):&#x20;
>     `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e`
>   </li>
>
>   <li>
>     US (devnet-us.magicblock.app):&#x20;
>     `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd`
>   </li>
>
>   <li>
>     TEE (devnet-tee.magicblock.app):&#x20;
>     `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo`
>   </li>
> </ul>
>
> **Localnet**
>
> <ul>
>   <li>
>     Local ER (localhost:7799):&#x20;
>     `mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev`
>   </li>
> </ul>

**3. [Commit PDA on ER](#3-commit)**

Test CPI hook to commit state account on ER

**4. [Undelegate PDA on ER](#4-undelegate)**

Test CPI hook to undelegate state account on ER

***

## Counter Example

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

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

### Code Snippets

> [tab] 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.
>
> ```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
> ```
>
> > [!NOTE]
> >
> > These public RPC endpoints are currently free and supported for development:
> > \
> > &#x20;Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) \\
> >
> > Solana Devnet: [https://api.devnet.solana.com](https://api.devnet.solana.com) \\
> >
> > ER Devnet (Asia): [https://devnet-as.magicblock.app](https://devnet-as.magicblock.app) \\
> >
> > ER Devnet (EU): [https://devnet-eu.magicblock.app](https://devnet-eu.magicblock.app) \\
> >
> > ER Devnet (US): [https://devnet-us.magicblock.app](https://devnet-us.magicblock.app) \\
> >
> > TEE Devnet: [https://devnet-tee.magicblock.app/](https://devnet-tee.magicblock.app/) \\
> >
> > Find out more details&#x20;
> > [here](https://docs.magicblock.gg/pages/ephemeral-rollups-ers/how-to-guide/local-development.md)
> > .
>
> ```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
> );
> ```
>
> [⬆️ Back to Top](#code-snippets)

> [tab] 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] [Transaction (Base Layer): Delegate](https://solscan.io/tx/5jUdf5rsfQsbLYAahS9axrnLnEjdbUqtXUmGfgGuS7QqbYJ4FZHgXTNoT1bxPXp7XQu78r8Ebpp1RT2u9V6qsc1r?cluster=devnet)
> >
> > Inspect transactions details on Solana Explorer
>
> ```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",
>   }
> );
> ```
>
> [⬆️ Back to Top](#code-snippets)

> [tab] 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.
>
> > [card] [Transaction (ER): Commit](https://solscan.io/tx/5GiFGyrnJPkEQbhE8EHVYczoj2RPGe1YSnoq1DzcUHAxpyzMUKtxG2Tc7TLkxtcCHr72ftnvmkAVMfecTaf6TCK8?cluster=custom\&customUrl=https://devnet.magicblock.app)
> >
> > Inspect transaction details on Solana Explorer
>
> > [card] [Transaction (Base layer): Commit](https://solscan.io/tx/5fHBADq99LAEBzGoeDXGtN3ut8RBf2s5UhbDM1N6TMTpvADNeYLz8e8vinNWj1VhLhrR7UxFoW7bo2u6pBR3YRjj?cluster=devnet)
> >
> > Inspect transaction details on Solana Explorer
>
> ```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",
>   }
> );
> ```
>
> [⬆️ Back to Top](#code-snippets)

> [tab] 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.
>
> > [card] [Transaction (ER): Undelegate](https://solscan.io/tx/bMN6AhXrGH93Uc6ALibGgjnE39hcnY57mBhYkZ8TRaKxNRvyFaweaQPBmDxPv81cgR47WTTzzhfziTUEgAT8Y5m?cluster=custom\&customUrl=https://devnet.magicblock.app)
> >
> > Inspect transaction details on Solana Explorer
>
> > [card] [Transaction (Base layer): Undelegate](https://solscan.io/tx/8JafYWiXmd4CHc2E97WKYnaNPmChZeg8aGYY7UUWaQ7Z54N5WoMcAVivyv2vdn9wKirMkR3y4UcmFPdXYqBtKAa?cluster=devnet)
> >
> > Inspect transaction details on Solana Explorer
>
> ```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",
>   }
> );
> ```
>
> [⬆️ Back to Top](#code-snippets)

***

## Solana Explorer

Get insights about your transactions and accounts on Solana:

> [card] [Solana Explorer](https://explorer.solana.com/)
>
> Official Solana Explorer

> [card] [Solscan](https://solscan.io/)
>
> Explore Solana Blockchain

## Solana RPC Providers

Send transactions and requests through existing RPC providers:

> [card] [Solana](https://solana.com/docs/references/clusters#on-a-high-level)
>
> Free Public Nodes

> [card] [Helius](https://www.helius.dev/solana-rpc-nodes)
>
> Free Shared Nodes

> [card] [Triton](https://triton.one/solana)
>
> Dedicated High-Performance Nodes

## Solana Validator Dashboard

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

> [card] [Solana Beach](https://solanabeach.io/)
>
> Get Validator Insights

> [card] [Validators App](https://www.validators.app/)
>
> Discover Validator Metrics

## Server Status

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

> [card] [Solana Status](https://status.solana.com/)
>
> Subscribe to Solana Server Updates

> [card] [MagicBlock Status](https://docs.magicblock.gg/pages/overview/additional-information/system-status.md)
>
> Subscribe to MagicBlock Server Status

***


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.