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

# 快速开始

> 了解如何使用 MagicBlock VRF SDK 请求并消费 Solana VRF 链上随机数。

***

<Tip>
  **正在使用 AI 编程助手开发？** 安装 MagicBlock Dev Skill，为你的助手提供 MagicBlock 专属开发模式——委托流程、Magic Actions、Crank、VRF 等。

  Claude Code 快速安装：

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

  使用 Cursor、Codex、Windsurf、Cline 或其他助手？请参阅 [AI Dev Skill](/cn/pages/overview/additional-information/ai-dev-skill) 页面了解所有安装方式。
</Tip>

### 快速访问

查看基础 VRF 示例：

<CardGroup cols={2}>
  <Card title="GitHub" icon="github" href="https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/roll-dice" iconType="duotone">
    掷骰子示例仓库
  </Card>

  <Card title="VRF dApp" icon="dice" href="https://roll-dice-demo.vercel.app/" iconType="duotone">
    在链上掷骰子
  </Card>

  <Card title="委托式 VRF dApp" icon="bolt" href="https://roll-dice-demo.vercel.app/delegated" iconType="duotone">
    在链上 100 毫秒内完成掷骰
  </Card>
</CardGroup>

***

<Note>
  需要先了解产品概览？请从 <a href="/cn/pages/verifiable-randomness-functions-vrfs/introduction/solana-vrf">Solana VRF</a> 页面开始，然后继续本快速开始。
</Note>

***

<Note>
  想在本机端到端运行 VRF？请使用 <a href="/cn/pages/get-started/how-integrate-your-program/local-setup">Local Validator Setup</a> 指南，了解完整本地栈、Surfpool 替代方案以及本地 <code>vrf-oracle</code> 流程。
</Note>

***

<div id="quickstart" />

## 分步指南

任何 Solana 程序都可以使用 MagicBlock VRF SDK 在数秒内请求并消费链上可验证随机数。完成本指南后，你将得到一个使用可验证随机数掷骰子的可运行示例。

<Steps>
  <Step title={<a href="#1-编写程序">编写你的程序</a>}>
    像平常一样编写你的 Solana 程序。
  </Step>

  <Step
    title={
  <a href="#2-请求并消费随机数">
    添加请求和消费随机数的指令。
  </a>
}
  >
    添加 CPI 钩子，通过已验证预言机的回调来请求并消费随机数。
  </Step>

  <Step title={<a href="#3-部署">将程序部署到 Solana</a>}>
    使用 Anchor CLI 部署你的 Solana 程序。
  </Step>

  <Step title={<a href="#4-测试">执行链上随机数交易。</a>}>
    发送交易以在链上生成并消费随机数。
  </Step>
</Steps>

***

<div id="roll-dice-example" />

## 掷骰子示例

<img
  src="https://mintcdn.com/magicblock-42/iteauKFqxDKE2Vln/images/gifs/vrf-roll-dice-420w.gif?s=9250f6e10d1a713f3c3d02f990f3a1b4"
  alt="Roll Dice GIF"
  style={{
width: "100%",
maxWidth: "420px",
height: "auto",
objectFit: "contain",
borderRadius: "8px",
}}
  width="420"
  height="420"
  data-path="images/gifs/vrf-roll-dice-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" />

### 代码片段

<Tabs>
  <Tab title="1. 编写程序">
    一个简单的掷骰子程序，玩家初始化状态账户来存储、请求并消费随机数：

    ```rust theme={null}
    pub const PLAYER: &[u8] = b"playerd";

    #[program]
    pub mod random_dice {
        use super::*;

        pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
            msg!(
                "Initializing player account: {:?}",
                ctx.accounts.player.key()
            );
            Ok(())
        }

        // ... Additional instructions will be added here
    }

    /// Context for initializing player
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(init_if_needed, payer = payer, space = 8 + 1, seeds = [PLAYER, payer.key().to_bytes().as_slice()], bump)]
        pub player: Account<'info, Player>,
        pub system_program: Program<'info, System>,
    }

    /// Player struct
    #[account]
    pub struct Player {
        pub last_result: u8,
    }
    ```

    [⬆️ 返回顶部](#code-snippets)
  </Tab>

  <Tab title="2. 请求并消费随机数">
    1. 将带有 Anchor 特性的 `ephemeral_vrf_sdk` 添加到你的程序中

    ```bash theme={null}
    cargo add ephemeral_vrf_sdk --features anchor
    ```

    导入 `vrf`、`create_request_randomness_ix`、`RequestRandomnessParams` 和 `SerializableAccountMeta`：

    ```rust theme={null}
    use ephemeral_vrf_sdk::anchor::vrf;
    use ephemeral_vrf_sdk::instructions::{create_request_randomness_ix, RequestRandomnessParams};
    use ephemeral_vrf_sdk::types::SerializableAccountMeta;
    ```

    2. 添加用于请求随机数的 `roll_dice` 指令，以及用于消费随机数的 `callback_roll_dice` 指令及其上下文：

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

        // ... `initialize` instruction

        // Request Randomness
        pub fn roll_dice(ctx: Context<DoRollDiceCtx>, client_seed: u8) -> Result<()> {
            msg!("Requesting randomness...");
            let ix = create_request_randomness_ix(RequestRandomnessParams {
                payer: ctx.accounts.payer.key(),
                oracle_queue: ctx.accounts.oracle_queue.key(),
                callback_program_id: ID,
                callback_discriminator: instruction::CallbackRollDice::DISCRIMINATOR.to_vec(),
                caller_seed: [client_seed; 32],
                // Specify any account that is required by the callback
                accounts_metas: Some(vec![SerializableAccountMeta {
                    pubkey: ctx.accounts.player.key(),
                    is_signer: false,
                    is_writable: true,
                }]),
                ..Default::default()
            });
            ctx.accounts
                .invoke_signed_vrf(&ctx.accounts.payer.to_account_info(), &ix)?;
            Ok(())
        }

        // Consume Randomness
        pub fn callback_roll_dice(
            ctx: Context<CallbackRollDiceCtx>,
            randomness: [u8; 32],
        ) -> Result<()> {
            let rnd_u8 = ephemeral_vrf_sdk::rnd::random_u8_with_range(&randomness, 1, 6);
            msg!("Consuming random number: {:?}", rnd_u8);
            let player = &mut ctx.accounts.player;
            player.last_result = rnd_u8; // Update the player's last result
            Ok(())
        }
    }

    #[vrf]
    #[derive(Accounts)]
    pub struct DoRollDiceCtx<'info> {
        #[account(mut)]
        pub payer: Signer<'info>,
        #[account(seeds = [PLAYER, payer.key().to_bytes().as_slice()], bump)]
        pub player: Account<'info, Player>,
        /// CHECK: The oracle queue
        #[account(mut, address = ephemeral_vrf_sdk::consts::DEFAULT_QUEUE)]
        pub oracle_queue: AccountInfo<'info>,
    }

    #[derive(Accounts)]
    pub struct CallbackRollDiceCtx<'info> {
        /// This check ensure that the vrf_program_identity (which is a PDA) is a singer
        /// enforcing the callback is executed by the VRF program trough CPI
        #[account(address = ephemeral_vrf_sdk::consts::VRF_PROGRAM_IDENTITY)]
        pub vrf_program_identity: Signer<'info>,
        #[account(mut)]
        pub player: Account<'info, Player>,
    }

    // ... Other context and account struct.
    ```

    <Note>
      **VRF SDK 常量**（`ephemeral_vrf_sdk::consts`）——请引用这些常量而不要硬编码地址，在程序和客户端/测试代码中均适用：

      | 常量                             | 用途                    | 地址                                             |
      | ------------------------------ | --------------------- | ---------------------------------------------- |
      | `VRF_PROGRAM_ID`               | VRF 程序                | `Vrf1RNUjXmQGjmQrQLvJHs9SNkvDJEsRVFPkfSQUwGz`  |
      | `VRF_PROGRAM_IDENTITY`         | 回调 signer PDA         | `9irBy75QS2BN81FUgXuHcjqceJJRuc9oDkAe8TKVvvAw` |
      | `DEFAULT_QUEUE`                | 基础层队列（Mainnet/Devnet） | `Cuj97ggrhhidhbu39TijNVqE74xvKJ69gDervRUXAxGh` |
      | `DEFAULT_EPHEMERAL_QUEUE`      | ER 队列（Mainnet/Devnet） | `5hBR571xnXppuCPveTrctfTU7tJLSN94nq7kv7FRK5Tc` |
      | `DEFAULT_TEST_QUEUE`           | 基础层队列（Localnet）       | `GKE6d7iv8kCBrsxr78W3xVdjGLLLJnxsGiuzrsZCGEvb` |
      | `DEFAULT_EPHEMERAL_TEST_QUEUE` | ER 队列（Localnet）       | `Sc9MJUngNbQXSXGP3F67KvKwVnhaYn6kcioxXNVowYT`  |

      将与交易运行位置相匹配的队列作为 `oracle_queue` 传入。Mainnet 和 Devnet 使用相同的队列地址；Localnet 使用测试队列。
    </Note>

    > `Request Randomness` 是生成一个随机 `hashId` 并附带相关回调指令的过程，用于触发已验证预言机。

    > `Consume Randomness` 是你的程序使用可验证随机数的过程，该随机数由已验证预言机提供并触发。

    [⬆️ 返回顶部](#code-snippets)
  </Tab>

  <Tab title="3. 部署">
    现在你的程序已经升级完成并准备就绪！将其构建并部署到目标集群：

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

    [⬆️ 返回顶部](#code-snippets)
  </Tab>

  <Tab title="4. 测试">
    准备好执行链上随机数交易吧！

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

    <Note>
      **VRF SDK 常量**（`ephemeral_vrf_sdk::consts`）——请引用这些常量而不要硬编码地址，在程序和客户端/测试代码中均适用：

      | 常量                             | 用途                    | 地址                                             |
      | ------------------------------ | --------------------- | ---------------------------------------------- |
      | `VRF_PROGRAM_ID`               | VRF 程序                | `Vrf1RNUjXmQGjmQrQLvJHs9SNkvDJEsRVFPkfSQUwGz`  |
      | `VRF_PROGRAM_IDENTITY`         | 回调 signer PDA         | `9irBy75QS2BN81FUgXuHcjqceJJRuc9oDkAe8TKVvvAw` |
      | `DEFAULT_QUEUE`                | 基础层队列（Mainnet/Devnet） | `Cuj97ggrhhidhbu39TijNVqE74xvKJ69gDervRUXAxGh` |
      | `DEFAULT_EPHEMERAL_QUEUE`      | ER 队列（Mainnet/Devnet） | `5hBR571xnXppuCPveTrctfTU7tJLSN94nq7kv7FRK5Tc` |
      | `DEFAULT_TEST_QUEUE`           | 基础层队列（Localnet）       | `GKE6d7iv8kCBrsxr78W3xVdjGLLLJnxsGiuzrsZCGEvb` |
      | `DEFAULT_EPHEMERAL_TEST_QUEUE` | ER 队列（Localnet）       | `Sc9MJUngNbQXSXGP3F67KvKwVnhaYn6kcioxXNVowYT`  |

      将与交易运行位置相匹配的队列作为 `oracle_queue` 传入。Mainnet 和 Devnet 使用相同的队列地址；Localnet 使用测试队列。
    </Note>

    运行以下测试：

    ```typescript theme={null}
    import * as anchor from "@coral-xyz/anchor";
    import { Program, web3 } from "@coral-xyz/anchor";
    import { RandomDice } from "../target/types/random_dice";

    describe("roll-dice", () => {
      // Configure the client to use the local cluster.
      anchor.setProvider(anchor.AnchorProvider.env());

      const program = anchor.workspace.RandomDice as Program<RandomDice>;

      it("Initialized player!", async () => {
        const tx = await program.methods.initialize().rpc();
        console.log("Your transaction signature", tx);
      });

      it("Do Roll Dice!", async () => {
        const tx = await program.methods.rollDice(0).rpc();
        console.log("Your transaction signature", tx);
        const playerPk = web3.PublicKey.findProgramAddressSync(
          [Buffer.from("playerd"), anchor.getProvider().publicKey.toBytes()],
          program.programId
        )[0];
        let player = await program.account.player.fetch(playerPk, "processed");
        await new Promise((resolve) => setTimeout(resolve, 3000));
        console.log("Player PDA: ", playerPk.toBase58());
        console.log("player: ", player);
      });
    });
    ```

    [⬆️ 返回顶部](#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="/cn/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="Ephemeral Rollup（ER）" icon="bolt" href="/cn/pages/ephemeral-rollups-ers/how-to-guide/quickstart" iconType="duotone">
    在 Solana 上安全执行实时、零手续费交易。
  </Card>

  <Card title="Private Ephemeral Rollup（PER）" icon="shield-check" href="/cn/pages/private-ephemeral-rollups-pers/how-to-guide/quickstart" iconType="duotone">
    在合规的前提下保护敏感数据——基于 Ephemeral Rollups 构建。
  </Card>

  <Card title="私密支付 API" icon="bag-shopping-plus" href="/cn/pages/private-ephemeral-rollups-pers/api-reference/per/introduction" iconType="duotone">
    几秒钟为你的应用集成链上私密转账——默认合规。
  </Card>

  <Card title="Solana VRF" icon="dice" href="/cn/pages/verifiable-randomness-functions-vrfs/introduction/solana-vrf" iconType="duotone">
    为游戏、抽奖和实时应用添加可证明公平的链上随机数。
  </Card>

  <Card title="价格预言机" icon="waveform" href="/cn/pages/tools/oracle/introduction" iconType="duotone">
    获取适用于交易和 DeFi 的低延迟链上价格数据。
  </Card>
</CardGroup>

***
