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

# クイックスタート

> どの Solana プログラムでも、delegation 機能を追加することで Ephemeral Rollups に対応できます。

***

<Tip>
  **AI コーディングエージェントで開発していますか？** MagicBlock Dev Skill をインストールすると、デリゲーションフロー、Magic Actions、Crank、VRF など、MagicBlock 固有の開発パターンをエージェントに提供できます。

  Claude Code でのクイックインストール：

  ```bash theme={null}
  npx add-skill https://github.com/magicblock-labs/magicblock-dev-skill
  ```

  Cursor、Codex、Windsurf、Cline などをお使いの場合は、[AI Dev Skill](/jp/pages/overview/additional-information/ai-dev-skill) ページですべてのインストール方法をご確認ください。
</Tip>

### クイックアクセス

基本的なカウンター例はこちらです。

<CardGroup cols={2}>
  <Card title="GitHub" icon="anchor" href="https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/anchor-counter" iconType="duotone">
    Anchor 実装
  </Card>

  <Card title="GitHub" icon="react" href="https://github.com/GabrielePicco/ephemeral-counter-ui" iconType="duotone">
    React 実装
  </Card>
</CardGroup>

***

<div
  style={{
position: "relative",
paddingBottom: "56.25%",
height: 0,
overflow: "hidden",
}}
>
  <iframe
    src="https://www.youtube.com/embed/qwu2RBKyFiw?si=PMg-3UbRfvvbrs7C&list=PLWR_ZQiGMS8mIe1kPZe8OfHIbhvZqaM8V"
    title="Build a real-time Anchor Counter on Solana with MagicBlock's Ephemeral Rollup | Tutorial"
    style={{
  position: "absolute",
  top: 0,
  left: 0,
  width: "100%",
  height: "100%",
}}
    frameBorder="0"
    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
    allowFullScreen
    referrerPolicy="strict-origin-when-cross-origin"
  />
</div>

***

<div id="quickstart" />

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

プログラムを構築し、MagicBlock の Delegation Program `DELeGGvXpWV2fqJUhqcF5ZSYMS4JTLjteaAMARRSaeSh` を使って delegation hooks を追加しアップグレードします。

<Steps>
  <Step title={<a href="#1-write-program">プログラムを書く</a>}>
    いつも通りに Solana プログラムを書きます。
  </Step>

  <Step
    title={
  <a href="#2-delegate">
    プログラムに delegation と undelegation hooks を追加する
  </a>
}
  >
    CPI hooks を追加し、状態アカウントを Ephemeral Rollup セッション経由で delegate、commit、undelegate できるようにします。

    <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-deploy">プログラムを Solana にデプロイする。</a>}>
    Anchor または Solana CLI を使ってプログラムを Solana に直接デプロイします。
  </Step>

  <Step
    title={
  <a href="#4-test">
    delegation とリアルタイム高速取引の実行準備
  </a>
}
  >
    SVM RPC 仕様に準拠したトランザクションを、変更なしでオンチェーン・オフチェーンの両方から送信します。
  </Step>
</Steps>

***

<div id="counter-example" />

## Counter 例

<img
  src="https://mintcdn.com/magicblock-42/iteauKFqxDKE2Vln/images/gifs/counter-420w.gif?s=f6feee67754b5b0b90c94ad159d4e630"
  alt="Counter GIF"
  style={{
width: "100%",
maxWidth: "420px",
height: "auto",
objectFit: "contain",
borderRadius: "8px",
}}
  width="420"
  height="420"
  data-path="images/gifs/counter-420w.gif"
/>

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

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

<div id="code-snippets" />

<div id="code-snippets-section" />

### コードスニペット

<Tabs>
  <Tab title="1. Write program">
    このプログラムは 2 つの主要 instruction を実装しています。

    1. `initialize`: カウンターを 0 に設定する
    2. `increment`: カウンターを 1 増やす

    また、カウンターの delegation と undelegation 用に次の instruction も実装しています。

    1. `Delegate`: カウンターを Base Layer から ER に委任する（Base Layer で呼ばれる）
    2. `CommitAndUndelegate`: カウンターを ER から Base Layer に同期するようスケジュールし、ER 上で undelegate する（ER で呼ばれる）
    3. `Commit`: カウンターを ER から Base Layer に同期するようスケジュールする（ER で呼ばれる）
    4. `Undelegate`:
       * カウンターの同期と undelegation をスケジュールする（ER で呼ばれる）
       * `#[ephemeral]` によって注入された callback instruction で undelegation が実行される（validator CPI を通じて Base Layer で呼ばれる）

    <Note>
      The undelegation callback discriminator `[196, 28, 41, 206, 48, 37, 51, 167]`
      and its instruction processor must be specified in your program. This
      instruction triggered by Delegation Program reverts account ownership on the
      Base Layer after calling undelegation on ER.

      With [`[#ephemeral]`](/jp/pages/ephemeral-rollups-ers/how-to-guide/quickstart#1-write-program) Anchor macro from MagicBlock's Ephemeral Rollup SDK, the undelegation callback discriminator and processor are injected into your program.
    </Note>

    ```rust theme={null}
    #[ephemeral]
    #[program]
    pub mod public_counter {
        use super::*;

        /// Initialize the counter.
        pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
            let counter = &mut ctx.accounts.counter;
            counter.count = 0;
            Ok(())
        }

        /// Increment the counter.
        pub fn increment(ctx: Context<Increment>) -> Result<()> {
            let counter = &mut ctx.accounts.counter;
            counter.count += 1;
            Ok(())
        }

        /// Delegate the account to the delegation program
        /// Set specific validator based on ER, see https://docs.magicblock.gg/pages/get-started/how-integrate-your-program/local-setup
        pub fn delegate(ctx: Context<DelegateInput>) -> Result<()> {
        // ...
        }

        /// Manually commit the counter state in the Ephemeral Rollup session.
        pub fn commit(ctx: Context<IncrementAndCommit>) -> Result<()> {
        // ...
        }

        /// Increment the counter and commit in the same instruction.
        pub fn increment_and_commit(ctx: Context<IncrementAndCommit>) -> Result<()> {
        // ...
        }

        /// Undelegate the account from the delegation program.
        pub fn undelegate(ctx: Context<IncrementAndCommit>) -> Result<()> {
        // ...
        }
    }

    pub const COUNTER_SEED: &[u8] = b"counter";

    /// Context for initializing counter
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(init_if_needed, payer = user, space = 8 + 8, seeds = [COUNTER_SEED], bump)]
        pub counter: Account<'info, Counter>,
        #[account(mut)]
        pub user: Signer<'info>,
        pub system_program: Program<'info, System>,
    }

    /// Context for incrementing counter
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(mut, seeds = [COUNTER_SEED], bump)]
        pub counter: Account<'info, Counter>,
    }

    /// Counter struct
    #[account]
    pub struct Counter {
        pub count: u64,
    }

    /// Other context for delegation
    ```

    特別なことはなく、単純な Anchor カウンタープログラムです。違いは、undelegation 用の `ephemeral` macro と、delegation program とやり取りするロジックを注入する `delegate` macro を追加していることです。

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

  <Tab title="2. Delegate">
    <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>

    1. Anchor 機能付き `ephemeral-rollups-sdk` をプログラムに追加する

    ```bash theme={null}
    cargo add ephemeral-rollups-sdk --features anchor
    ```

    `delegate`、`commit`、`ephemeral`、`DelegateConfig`、`commit_accounts`、`commit_and_undelegate_accounts` をインポートします。

    ```rust theme={null}
    use ephemeral_rollups_sdk::anchor::{
      commit,
      delegate,
      ephemeral
    };
    use ephemeral_rollups_sdk::cpi::DelegateConfig;
    use ephemeral_rollups_sdk::ephem::{
      commit_accounts,
      commit_and_undelegate_accounts
      };
    ```

    2. プログラムに `delegate` macro と instruction、`ephemeral` macro、`undelegate` instruction を追加します。auto commit や特定 ER validator など、好みの delegation config も指定できます。

    ```rust theme={null}
    /// Add delegate function to the context
    #[delegate]
    #[derive(Accounts)]
    pub struct DelegateInput<'info> {
        pub payer: Signer<'info>,
        /// CHECK: The pda to delegate
        #[account(mut, del)]
        pub pda: AccountInfo<'info>,
    }
    ```

    ```rust theme={null}
    /// Delegate the account to the delegation program
    /// Set specific validator based on ER, see https://docs.magicblock.gg/pages/get-started/how-integrate-your-program/local-setup
    pub fn delegate(ctx: Context<DelegateInput>) -> Result<()> {
        ctx.accounts.delegate_pda(
            &ctx.accounts.payer,
            &[COUNTER_SEED],
            DelegateConfig {
                // Optionally set a specific validator from the first remaining account
                validator: ctx.remaining_accounts.first().map(|acc| acc.key()),
                ..Default::default()
            },
        )?;
        Ok(())
    }
    ```

    ```rust theme={null}
    use ephemeral_rollups_sdk::ephem::MagicIntentBundleBuilder;

    /// Manually commit the counter state in the Ephemeral Rollup session.
    pub fn commit(ctx: Context<IncrementAndCommit>) -> Result<()> {
        MagicIntentBundleBuilder::new(
            ctx.accounts.payer.to_account_info(),
            ctx.accounts.magic_context.to_account_info(),
            ctx.accounts.magic_program.to_account_info(),
        )
        .commit(&[ctx.accounts.counter.to_account_info()])
        .build_and_invoke()?;
        Ok(())
    }

    /// Increment the counter and commit the new state in the same instruction.
    pub fn increment_and_commit(ctx: Context<IncrementAndCommit>) -> Result<()> {
        let counter = &mut ctx.accounts.counter;
        counter.count += 1;
        // Serialize the Anchor account before the CPI sees it
        counter.exit(&crate::ID)?;
        MagicIntentBundleBuilder::new(
            ctx.accounts.payer.to_account_info(),
            ctx.accounts.magic_context.to_account_info(),
            ctx.accounts.magic_program.to_account_info(),
        )
        .commit(&[ctx.accounts.counter.to_account_info()])
        .build_and_invoke()?;
        Ok(())
    }
    ```

    ```rust theme={null}
    use ephemeral_rollups_sdk::ephem::MagicIntentBundleBuilder;

    /// Undelegate the account from the delegation program.
    /// Commits the latest state and returns ownership of the PDA back to the owner program.
    pub fn undelegate(ctx: Context<IncrementAndCommit>) -> Result<()> {
        MagicIntentBundleBuilder::new(
            ctx.accounts.payer.to_account_info(),
            ctx.accounts.magic_context.to_account_info(),
            ctx.accounts.magic_program.to_account_info(),
        )
        .commit_and_undelegate(&[ctx.accounts.counter.to_account_info()])
        .build_and_invoke()?;
        Ok(())
    }
    ```

    > `Delegation` は、プログラムの 1 つ以上の `PDA` の所有権を delegation program に移す処理です。これにより Ephemeral Validators はその `PDA` を使って SVM runtime 上でトランザクションを実行できます。

    > `Commit` は `PDA` の状態を ER から base layer に更新する処理です。finalization の後も `PDA` は base layer 上でロックされたままです。

    > `Undelegation` は `PDA` の所有権をプログラムへ戻す処理です。undelegation 時には状態がコミットされ、finalization プロセスが始まります。状態検証が完了すると、`PDA` はアンロックされ、base layer 上で通常通り使えるようになります。

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

  <Tab title="3. Deploy">
    これでプログラムのアップグレードは完了です。対象 cluster へビルドしてデプロイします。

    ```bash theme={null}
    anchor build && anchor deploy
    ```

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

  <Tab title="4. Test">
    これで delegation とリアルタイム高速取引を実行する準備が整いました。

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

    ```bash theme={null}
    anchor test --skip-build --skip-deploy --skip-local-validator
    ```

    次のテストを実行します。

    ```typescript theme={null}
    const COUNTER_SEED = "counter";

    // Set Anchor providers
    const provider = new anchor.AnchorProvider(
      new anchor.web3.Connection(
        process.env.PROVIDER_ENDPOINT || "https://api.devnet.solana.com",
        {
          wsEndpoint: process.env.PROVIDER_WS_ENDPOINT || undefined,
          commitment: "confirmed",
        },
      ),
      anchor.Wallet.local(),
    );
    anchor.setProvider(provider);

    const providerEphemeralRollup = new anchor.AnchorProvider(
      new anchor.web3.Connection(
        process.env.EPHEMERAL_PROVIDER_ENDPOINT ||
          "https://devnet-as.magicblock.app/",
        {
          wsEndpoint:
            process.env.EPHEMERAL_WS_ENDPOINT || "wss://devnet-as.magicblock.app/",
          commitment: "confirmed",
        },
      ),
      anchor.Wallet.local(),
    );

    // Set program and PDA
    const program = anchor.workspace.PublicCounter as Program<PublicCounter>;
    const [counterPDA] = anchor.web3.PublicKey.findProgramAddressSync(
      [Buffer.from(COUNTER_SEED)],
      program.programId,
    );

    // Initialize counter on base layer
    let initTx = await program.methods
      .initialize()
      .accounts({
        user: provider.wallet.publicKey,
      })
      .transaction();
    const initTxHash = await provider.sendAndConfirm(initTx, [
      provider.wallet.payer,
    ]);

    // Increment counter on base layer
    let incBaseTx = await program.methods
      .increment()
      .accounts({
        counter: counterPDA,
      })
      .transaction();
    const incBaseTxHash = await provider.sendAndConfirm(incBaseTx, [
      provider.wallet.payer,
    ]);

    // Delegate counter to ER
    // Pin a specific validator by passing it in remaining_accounts
    const ER_VALIDATOR = new anchor.web3.PublicKey(
      "MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57", // Asia ER validator
    );
    let delTx = await program.methods
      .delegate()
      .accounts({
        payer: provider.wallet.publicKey,
        pda: counterPDA,
      })
      .remainingAccounts([
        { pubkey: ER_VALIDATOR, isSigner: false, isWritable: false },
      ])
      .transaction();
    const delTxHash = await provider.sendAndConfirm(delTx, [
      provider.wallet.payer,
    ]);

    // Increment counter in real time on ER
    let incErTx = await program.methods
      .increment()
      .accounts({
        counter: counterPDA,
      })
      .transaction();
    incErTx.feePayer = providerEphemeralRollup.wallet.publicKey;
    incErTx.recentBlockhash = (
      await providerEphemeralRollup.connection.getLatestBlockhash()
    ).blockhash;
    incErTx = await providerEphemeralRollup.wallet.signTransaction(incErTx);
    const incErTxHash = await providerEphemeralRollup.sendAndConfirm(incErTx);

    // Commit and undelegate counter from ER back to base layer
    let undelTx = await program.methods
      .undelegate()
      .accounts({
        payer: providerEphemeralRollup.wallet.publicKey,
      })
      .transaction();
    undelTx.feePayer = providerEphemeralRollup.wallet.publicKey;
    undelTx.recentBlockhash = (
      await providerEphemeralRollup.connection.getLatestBlockhash()
    ).blockhash;
    undelTx = await providerEphemeralRollup.wallet.signTransaction(undelTx);
    const undelTxHash = await providerEphemeralRollup.sendAndConfirm(undelTx);
    ```

    フロントエンド統合を簡単にするために [Magic Router](/jp/pages/ephemeral-rollups-ers/introduction/magic-router) を用意しました。トランザクションを magic router に送るだけで、それが [Ephemeral Rollup](/jp/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) に行くべきか base layer に行くべきかを自動で判断できます。

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

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

***

<div id="advanced-code-snippets" />

### 高度なコードスニペット

<Tabs>
  <Tab title="Resize PDA">
    委任済み PDA をリサイズする際には:

    * 新しいアカウントサイズでも rent-exempt を保てるだけの lamports が PDA に必要です。
    * 追加 lamports が必要な場合、差額を提供するために **payer account も委任済みである必要があります**。
    * PDA はプログラム所有である必要があり、lamports 転送に必要な signer をトランザクションに含める必要があります。
    * `system_instruction::allocate` を使用します。

    ```rust theme={null}
    #[account]
    pub struct Counter {
        pub count: u64,
        pub extra_data: Vec<u8>,
    }

    #[derive(Accounts)]
    pub struct ResizeCounter<'info> {
        #[account(mut)]
        pub counter: Account<'info, Counter>,
        #[account(mut)]
        pub payer: Signer<'info>,
        pub system_program: Program<'info, System>,
    }

        // Resize the counter (e.g., to store more extra_data)
        pub fn resize_counter(ctx: Context<ResizeCounter>, new_size: usize) -> Result<()> {
            let account_to_resize = &mut ctx.accounts.counter.to_account_info();
            let payer = &mut ctx.accounts.payer.to_account_info();

            // Calculate rent-exemption for the new size
            let rent = Rent::get()?;
            let min_balance = rent.minimum_balance(new_size);

            // Top up lamports if needed
            let current_lamports = **account_to_resize.lamports.borrow();
            if current_lamports < min_balance {
                let to_transfer = min_balance - current_lamports;
                **payer.try_borrow_mut_lamports()? -= to_transfer;
                **account_to_resize.try_borrow_mut_lamports()? += to_transfer;
            }

            // Resize account
            account_to_resize.resize(new_size)?;

            Ok(())
        }
    ```

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

  <Tab title="Magic Router">
    動的にトランザクションを送る前に、まず Magic Router との接続を初期化します。

    <Note>
      これらの公開 RPC エンドポイントは現在無料で、開発用途に利用できます:
      <br /> Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) <br />
    </Note>

    初期化、送信、確認に使う好みの SDK を選んでください。

    * `ephemeral-rollups-kit` は `@solana/kit` 向け
    * `ephemeral-rollups-sdk` は `@solana/web.js` 向け

    <CodeGroup>
      ```typescript Kit theme={null}
      import { Connection } from "@magicblock-labs/ephemeral-rollups-kit";

      // Initialize connection
      const connection = await Connection.create(
        "https://devnet-router.magicblock.app",
        "wss://devnet-router.magicblock.app"
      );

      // ... create transaction

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

      ```typescript Web3.js theme={null}
      import { sendAndConfirmTransaction } from "@solana/web3.js";
      import { ConnectionMagicRouter } from "@magicblock-labs/ephemeral-rollups-sdk";

      // Initialize connection
      const connection = new ConnectionMagicRouter(
        "https://devnet-router.magicblock.app/",
        { wsEndpoint: "wss://devnet-router.magicblock.app/" }
      );

      // ... create transaction

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

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

  <Tab title="Magic Action">
    ### クイックアクセス

    <CardGroup cols={2}>
      <Card title="Magic Actions Example" icon="code" href="https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/magic-actions" iconType="duotone">
        GitHub 上の参考実装を見る
      </Card>
    </CardGroup>

    Ephemeral Rollup
    (ER) commit の直後に Solana base layer 上で自動実行される instruction を 1 つ以上アタッチします。
    [Magic Action について詳しく見る](/jp/pages/ephemeral-rollups-ers/magic-actions/overview.mdx)

    ### 1) アクション命令を作成する

    `update_leaderboard` 命令はコミット完了直後にベースレイヤーで実行されます。アカウントコンテキストに付与された `#[action]` 属性により、コミット後アクションから呼び出し可能であることが示されます。

    ```rust theme={null}
    // program instruction
    pub fn update_leaderboard(ctx: Context<UpdateLeaderboard>) -> Result<()> {
        let leaderboard = &mut ctx.accounts.leaderboard;
        let counter_info = &mut ctx.accounts.counter.to_account_info();
        let mut data: &[u8] = &counter_info.try_borrow_data()?;
        let counter = Counter::try_deserialize(&mut data)?;

        if counter.count > leaderboard.high_score {
            leaderboard.high_score = counter.count;
        }

        msg!(
            "Leaderboard updated! High score: {}",
            leaderboard.high_score
        );
        Ok(())
    }

    // instruction context
    #[action]
    #[derive(Accounts)]
    pub struct UpdateLeaderboard<'info> {
        #[account(mut, seeds = [LEADERBOARD_SEED], bump)]
        pub leaderboard: Account<'info, Leaderboard>,
        /// CHECK: PDA owner depends on: 1) Delegated: Delegation Program; 2) Undelegated: Your program ID
        pub counter: UncheckedAccount<'info>,
    }
    ```

    ### 2) アクション付きコミット命令を構築する

    `commit_and_update_leaderboard` コミット命令は ER 上で実行されます。`MagicIntentBundleBuilder` を使用してコミットとコミット後アクションの両方を `magic_context` に予約します — ER トランザクションがベースレイヤーへ確定されるとき、両者は同時に適用されます。

    ```rust theme={null}
    // commit action instruction on ER
    pub fn commit_and_update_leaderboard(ctx: Context<CommitAndUpdateLeaderboard>) -> Result<()> {
        // Build the post-commit action that updates the leaderboard on base layer
        let instruction_data =
            anchor_lang::InstructionData::data(&crate::instruction::UpdateLeaderboard {});
        let action_args = ActionArgs::new(instruction_data);
        let action_accounts = vec![
            ShortAccountMeta {
                pubkey: ctx.accounts.leaderboard.key(),
                is_writable: true,
            },
            ShortAccountMeta {
                pubkey: ctx.accounts.counter.key(),
                is_writable: false,
            },
        ];
        let action = CallHandler {
            destination_program: crate::ID,
            accounts: action_accounts,
            args: action_args,
            // Signer that pays transaction fees for the action from its escrow PDA
            escrow_authority: ctx.accounts.payer.to_account_info(),
            compute_units: 200_000,
        };

        // Schedule commit + post-commit action on magic_context
        MagicIntentBundleBuilder::new(
            ctx.accounts.payer.to_account_info(),
            ctx.accounts.magic_context.to_account_info(),
            ctx.accounts.magic_program.to_account_info(),
        )
        .commit(&[ctx.accounts.counter.to_account_info()])
        .add_post_commit_actions([action])
        .build_and_invoke()?;

        Ok(())
    }

    // commit action context on ER
    #[commit]
    #[derive(Accounts)]
    pub struct CommitAndUpdateLeaderboard<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,

        #[account(mut, seeds = [COUNTER_SEED], bump)]
        pub counter: Account<'info, Counter>,

        /// CHECK: Leaderboard PDA - not mut here, writable set in handler
        #[account(seeds = [LEADERBOARD_SEED], bump)]
        pub leaderboard: UncheckedAccount<'info>,

        /// CHECK: Your program ID
        pub program_id: AccountInfo<'info>,
    }
    ```

    ### 複数のアクションを実行する

    複数のアカウントをコミットし、複数のアクションを 1 回の呼び出しで連鎖させることができます。アクションは `add_post_commit_actions` に渡された順序で順次実行されます。

    ```rust theme={null}
    // Chain several actions — they execute sequentially on base layer after the commit lands.
    MagicIntentBundleBuilder::new(
        ctx.accounts.payer.to_account_info(),
        ctx.accounts.magic_context.to_account_info(),
        ctx.accounts.magic_program.to_account_info(),
    )
    .commit(&[
        ctx.accounts.counter.to_account_info(),
        // ... additional committed accounts
    ])
    .add_post_commit_actions([action_1, action_2, action_3])
    .build_and_invoke()?;
    ```

    ### 委任解除と一緒にアクションを実行する

    アクションは委任解除にも連鎖できます — counter のコミット、委任解除、アクションすべてが同一の ER トランザクション内でアトミックに実行されます。

    ```rust theme={null}
    // Commit, undelegate, AND execute actions — all atomically on base layer after the ER transaction seals.
    MagicIntentBundleBuilder::new(
        ctx.accounts.payer.to_account_info(),
        ctx.accounts.magic_context.to_account_info(),
        ctx.accounts.magic_program.to_account_info(),
    )
    .commit_and_undelegate(&[ctx.accounts.counter.to_account_info()])
    .add_post_commit_actions([action])
    .build_and_invoke()?;
    ```

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

  <Tab title="委任済みアカウントへの lamports チャージ">
    委任済みアカウントに lamports を追加チャージします。トランザクションは **base layer** で提出し、Ephemeral SPL Token プログラムが使い捨ての lamports PDA を介して委任済み残高へ lamports を送り込みます。

    主な用途：委任済み fee payer に資金を補充し、デフォルトで提供される 10 回の commit スポンサーシップ枠を超えても委任済み fee payer 自身で commit 費用を支払えるようにします。

    ポイント：

    * チャージごとに `crypto.getRandomValues` で新しい 32 バイトの salt を生成します — salt を使い回すと既存の PDA と衝突します。
    * ER ではなく **base layer の RPC** に提出します。
    * 送金先アカウントはすでに委任済みである必要があります。

    ```typescript theme={null}
    import {
      Connection,
      Keypair,
      PublicKey,
      Transaction,
      sendAndConfirmTransaction,
    } from "@solana/web3.js";
    import {
      lamportsDelegatedTransferIx,
      deriveLamportsPda,
    } from "@magicblock-labs/ephemeral-rollups-sdk";

    /**
     * Top up a delegated account with lamports.
     *
     * The transaction is submitted on the BASE LAYER. The Ephemeral SPL Token
     * program creates a single-use lamports PDA, funds it from the payer, and
     * delegates it so the ER credits the destination's delegated balance.
     */
    async function topUpDelegatedAccount(
      connection: Connection,         // base-layer connection
      payer: Keypair,
      destination: PublicKey,         // delegated account to top up
      amountLamports: bigint,
    ) {
      // Generate a fresh 32-byte salt per top-up.
      // Re-using a salt collides with an existing lamports PDA and the call fails.
      const salt = crypto.getRandomValues(new Uint8Array(32));

      const [lamportsPda] = deriveLamportsPda(payer.publicKey, destination, salt);

      const ix = await lamportsDelegatedTransferIx(
        payer.publicKey,
        destination,
        amountLamports,
        salt,
      );

      const tx = new Transaction().add(ix);
      tx.feePayer = payer.publicKey;

      // CRITICAL: send to the base-layer RPC, not the ER.
      const sig = await sendAndConfirmTransaction(connection, tx, [payer], {
        commitment: "confirmed",
        skipPreflight: true,
      });

      return { sig, lamportsPda };
    }
    ```

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

  <Tab title="On-Curve Delegation">
    ### クイックアクセス

    <CardGroup cols={2}>
      <Card title="GitHub" icon="wallet" href="https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/oncurve-delegation" iconType="duotone">
        オンカーブ委任
      </Card>
    </CardGroup>

    オンカーブアカウントを委任するために必要な署名者:

    1. 委任対象のオンカーブアカウント
    2. 手数料支払い者

    オンカーブアカウントを委任するために必要な命令:

    1. System Account を Delegation Program に割り当てる
    2. Delegation Program に委任する

    <CodeGroup>
      ```typescript Kit theme={null}
      // Create assign instruction
      // The on-curve account must sign this instruction to change its owner
      const accountSigner = await cryptoKeyPairToTransactionSigner(userKeypair);
      const delegationProgramAddress = address(DELEGATION_PROGRAM_ID.toString());
      const assignInstruction = getAssignInstruction({
        account: accountSigner,
        programAddress: delegationProgramAddress,
      });

      // Create delegate instruction
      const delegateInstruction = await createDelegateInstruction({
        payer: feePayerAddress,
        delegatedAccount: userAddress,
        ownerProgram: ownerProgramAddress,
        validator: validatorAddress,
      });

      // Prepare transaction
      const transactionMessage = pipe(
        createTransactionMessage({ version: 0 }),
        (tx) => setTransactionMessageFeePayer(feePayerAddress, tx),
        (tx) =>
          appendTransactionMessageInstructions(
            [assignInstruction, delegateInstruction],
            tx
          )
      );
      // Send and confirm transaction (fee payer need to sign, on-curve account cannot be signer since delegated)
      const txHash = await connection.sendAndConfirmTransaction(
        transactionMessage,
        [userKeypair, feePayerKeypair],
        { commitment: "confirmed", skipPreflight: true }
      );
      ```

      ```typescript Web3.js theme={null}
      // Create assign instruction
      const assignInstruction = SystemProgram.assign({
        accountPubkey: userPubkey,
        programId: DELEGATION_PROGRAM_ID,
      });

      // Create delegate instruction
      const delegateInstruction = createDelegateInstruction({
        payer: feePayerKeypair.publicKey,
        delegatedAccount: userPubkey,
        ownerProgram: ownerProgram,
        validator: validator,
      });

      // Create and send transaction (fee payer need to sign, on-curve account cannot be signer since delegated)
      const tx = new Transaction().add(assignInstruction, delegateInstruction);
      tx.feePayer = feePayerKeypair.publicKey;
      const txSignature = await sendAndConfirmTransaction(
        connectionBaseLayer,
        tx,
        [userKeypair, feePayerKeypair],
        {
          skipPreflight: true,
        }
      );
      ```
    </CodeGroup>

    直接の commit と undelegate は Magic Program 経由でのみ行います。

    <CodeGroup>
      ```typescript Kit theme={null}
      // Create commit and undelegate instruction
      const commitAndUndelegateInstruction = createCommitAndUndelegateInstruction(
        userAddress,
        [userAddress]
      );

      // Prepare transaction
      const transactionMessage = pipe(
        createTransactionMessage({ version: 0 }),
        (tx) => setTransactionMessageFeePayer(feePayerAddress, tx),
        (tx) =>
          appendTransactionMessageInstructions([commitAndUndelegateInstruction], tx)
      );

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

      ```typescript Web3.js theme={null}
      // Create commit and undelegate instruction
      const commitAndUndelegateInstruction = createCommitAndUndelegateInstruction(
        userPubkey,
        [userPubkey]
      );

      // Send and confirm transaction on ephemeral connection
      const tx = new Transaction().add(commitAndUndelegateInstruction);
      tx.feePayer = feePayerKeypair.publicKey;
      const txSignature = await sendAndConfirmTransaction(
        ephemeralConnection,
        tx,
        [userKeypair, feePayerKeypair],
        {
          skipPreflight: true,
        }
      );
      ```
    </CodeGroup>

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

***

### クイックアクセス

Private ER、Rust Native 実装、ローカル開発についてさらに学びましょう。

<CardGroup>
  <Card title="Private Ephemeral Rollups (PER)" icon="anchor" href="/jp/pages/private-ephemeral-rollups-pers/how-to-guide/quickstart" iconType="duotone">
    クイックスタート
  </Card>

  <Card title="Rust Native" icon="rust" href="/jp/pages/ephemeral-rollups-ers/how-to-guide/rust-program" iconType="duotone">
    クイックスタート
  </Card>

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

***

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

***

<div id="magicblock-products" />

## MagicBlock 製品

<CardGroup cols={2}>
  <Card title="エフェメラルロールアップ（ER）" icon="bolt" href="/jp/pages/ephemeral-rollups-ers/how-to-guide/quickstart" iconType="duotone">
    Solana 上でリアルタイムかつ手数料ゼロのトランザクションを安全に実行します。
  </Card>

  <Card title="プライベート・エフェメラルロールアップ（PER）" icon="shield-check" href="/jp/pages/private-ephemeral-rollups-pers/how-to-guide/quickstart" iconType="duotone">
    コンプライアンスを保ちながら機密データを保護 — Ephemeral Rollups の上に構築されています。
  </Card>

  <Card title="プライベート決済 API" icon="bag-shopping-plus" href="/jp/pages/private-ephemeral-rollups-pers/api-reference/per/introduction" iconType="duotone">
    あなたのアプリにオンチェーンのプライベート送金を数秒で統合 — コンプライアンスもデフォルトで備わっています。
  </Card>

  <Card title="Solana VRF" icon="dice" href="/jp/pages/verifiable-randomness-functions-vrfs/introduction/solana-vrf" iconType="duotone">
    ゲーム、抽選、リアルタイムアプリに証明可能に公平なオンチェーンランダムネスを追加します。
  </Card>

  <Card title="価格オラクル" icon="waveform" href="/jp/pages/tools/oracle/introduction" iconType="duotone">
    取引や DeFi 向けの低遅延オンチェーン価格フィードにアクセスできます。
  </Card>
</CardGroup>

***
