magicblock

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MagicBlock Ephemeral Rollups Guide

MagicBlock Ephemeral Rollups 指南

A comprehensive guide for building high-performance Solana applications with MagicBlock Ephemeral Rollups - enabling sub-10ms latency and gasless transactions.
本指南全面介绍如何使用MagicBlock Ephemeral Rollups构建高性能Solana应用,实现亚10毫秒延迟与免Gas交易。

Overview

概述

MagicBlock Ephemeral Rollups (ER) are specialized SVM runtimes that enhance Solana with:
  • Sub-10ms latency (vs ~400ms on base Solana)
  • Gasless transactions for seamless UX
  • Full composability with existing Solana programs
  • Horizontal scaling via on-demand rollups
MagicBlock Ephemeral Rollups(ER)是专用的SVM运行时,为Solana带来以下增强特性:
  • 亚10毫秒延迟(对比基础Solana的约400毫秒)
  • 免Gas交易,提供流畅的用户体验
  • 与现有Solana程序完全兼容
  • 通过按需Rollups实现水平扩展

Architecture

架构

┌─────────────────────────────────────────────────────────────┐
│                      Your Application                        │
├─────────────────────────────────────────────────────────────┤
│  Base Layer (Solana)          │  Ephemeral Rollup (ER)      │
│  - Initialize accounts        │  - Execute operations       │
│  - Delegate accounts          │  - Process at ~10-50ms      │
│  - Final state commits        │  - Zero gas fees            │
│  - ~400ms finality            │  - Commit state to Solana   │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│                      Your Application                        │
├─────────────────────────────────────────────────────────────┤
│  Base Layer (Solana)          │  Ephemeral Rollup (ER)      │
│  - Initialize accounts        │  - Execute operations       │
│  - Delegate accounts          │  - Process at ~10-50ms      │
│  - Final state commits        │  - Zero gas fees            │
│  - ~400ms finality            │  - Commit state to Solana   │
└─────────────────────────────────────────────────────────────┘

Core Flow

核心流程

  1. Initialize - Create accounts on Solana base layer
  2. Delegate - Transfer account ownership to delegation program
  3. Execute - Run fast operations on Ephemeral Rollup
  4. Commit - Sync state back to base layer
  5. Undelegate - Return ownership to your program
  1. 初始化 - 在Solana基础层创建账户
  2. 委托 - 将账户所有权转移至委托程序
  3. 执行 - 在Ephemeral Rollup上运行快速操作
  4. 提交 - 将状态同步回基础层
  5. 撤销委托 - 将账户所有权返还给你的程序

Prerequisites

前置条件

bash
undefined
bash
undefined

Required versions

所需版本

Solana: 2.3.13 Rust: 1.85.0 Anchor: 0.32.1 Node: 24.10.0
Solana: 2.3.13 Rust: 1.85.0 Anchor: 0.32.1 Node: 24.10.0

Install Anchor (if needed)

安装Anchor(如有需要)

cargo install --git https://github.com/coral-xyz/anchor anchor-cli
undefined
cargo install --git https://github.com/coral-xyz/anchor anchor-cli
undefined

Quick Start

快速开始

1. Add Dependencies (Cargo.toml)

1. 添加依赖(Cargo.toml)

toml
[dependencies]
anchor-lang = "0.32.1"
ephemeral-rollups-sdk = { version = "0.6.5", features = ["anchor", "disable-realloc"] }
toml
[dependencies]
anchor-lang = "0.32.1"
ephemeral-rollups-sdk = { version = "0.6.5", features = ["anchor", "disable-realloc"] }

2. Program Setup (lib.rs)

2. 程序设置(lib.rs)

rust
use anchor_lang::prelude::*;
use ephemeral_rollups_sdk::anchor::{delegate_account, commit_accounts, ephemeral};
use ephemeral_rollups_sdk::cpi::DelegationProgram;

declare_id!("YourProgramId111111111111111111111111111111");

#[ephemeral]  // Required: enables ER support
#[program]
pub mod my_program {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.state.value = 0;
        Ok(())
    }

    #[delegate]  // Auto-injects delegation accounts
    pub fn delegate(ctx: Context<Delegate>) -> Result<()> {
        Ok(())
    }

    pub fn increment(ctx: Context<Update>) -> Result<()> {
        ctx.accounts.state.value += 1;
        Ok(())
    }

    #[commit]  // Auto-injects commit accounts
    pub fn undelegate(ctx: Context<Undelegate>) -> Result<()> {
        Ok(())
    }
}
rust
use anchor_lang::prelude::*;
use ephemeral_rollups_sdk::anchor::{delegate_account, commit_accounts, ephemeral};
use ephemeral_rollups_sdk::cpi::DelegationProgram;

declare_id!("YourProgramId111111111111111111111111111111");

#[ephemeral]  // 必需:启用ER支持
#[program]
pub mod my_program {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.state.value = 0;
        Ok(())
    }

    #[delegate]  // 自动注入委托账户
    pub fn delegate(ctx: Context<Delegate>) -> Result<()> {
        Ok(())
    }

    pub fn increment(ctx: Context<Update>) -> Result<()> {
        ctx.accounts.state.value += 1;
        Ok(())
    }

    #[commit]  // 自动注入提交账户
    pub fn undelegate(ctx: Context<Undelegate>) -> Result<()> {
        Ok(())
    }
}

3. TypeScript Client Setup

3. TypeScript客户端设置

typescript
import { Connection, PublicKey } from "@solana/web3.js";
import { AnchorProvider, Program } from "@coral-xyz/anchor";
import { DELEGATION_PROGRAM_ID } from "@magicblock-labs/ephemeral-rollups-sdk";

// CRITICAL: Separate connections for each layer
const baseConnection = new Connection("https://api.devnet.solana.com");
const erConnection = new Connection("https://devnet.magicblock.app");

// Create providers
const baseProvider = new AnchorProvider(baseConnection, wallet, { commitment: "confirmed" });
const erProvider = new AnchorProvider(erConnection, wallet, {
  commitment: "confirmed",
  skipPreflight: true,  // Required for ER
});

// Check delegation status
async function isDelegated(pubkey: PublicKey): Promise<boolean> {
  const info = await baseConnection.getAccountInfo(pubkey);
  return info?.owner.equals(DELEGATION_PROGRAM_ID) ?? false;
}
typescript
import { Connection, PublicKey } from "@solana/web3.js";
import { AnchorProvider, Program } from "@coral-xyz/anchor";
import { DELEGATION_PROGRAM_ID } from "@magicblock-labs/ephemeral-rollups-sdk";

// 重要:为基础层和ER分别维护连接
const baseConnection = new Connection("https://api.devnet.solana.com");
const erConnection = new Connection("https://devnet.magicblock.app");

// 创建提供者
const baseProvider = new AnchorProvider(baseConnection, wallet, { commitment: "confirmed" });
const erProvider = new AnchorProvider(erConnection, wallet, {
  commitment: "confirmed",
  skipPreflight: true,  // ER必需
});

// 检查委托状态
async function isDelegated(pubkey: PublicKey): Promise<boolean> {
  const info = await baseConnection.getAccountInfo(pubkey);
  return info?.owner.equals(DELEGATION_PROGRAM_ID) ?? false;
}

Key Concepts

核心概念

Delegation

委托

Delegation transfers PDA ownership to the delegation program, allowing the Ephemeral Validator to process transactions.
rust
#[derive(Accounts)]
pub struct Delegate<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,
    /// CHECK: Will be delegated
    #[account(mut, del)]  // 'del' marks for delegation
    pub state: AccountInfo<'info>,
    pub delegation_program: Program<'info, DelegationProgram>,
}
委托操作会将PDA所有权转移至委托程序,允许Ephemeral验证器处理交易。
rust
#[derive(Accounts)]
pub struct Delegate<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,
    /// CHECK: 即将被委托
    #[account(mut, del)]  // 'del'标记为待委托账户
    pub state: AccountInfo<'info>,
    pub delegation_program: Program<'info, DelegationProgram>,
}

Commit

提交

Commits update PDA state from ER to base layer without undelegating.
rust
use ephemeral_rollups_sdk::anchor::commit_accounts;

pub fn commit(ctx: Context<Commit>) -> Result<()> {
    commit_accounts(
        &ctx.accounts.payer,
        vec![&ctx.accounts.state.to_account_info()],
        &ctx.accounts.magic_context,
        &ctx.accounts.magic_program,
    )?;
    Ok(())
}
提交操作会将ER上的PDA状态更新同步至基础层,无需撤销委托。
rust
use ephemeral_rollups_sdk::anchor::commit_accounts;

pub fn commit(ctx: Context<Commit>) -> Result<()> {
    commit_accounts(
        &ctx.accounts.payer,
        vec![&ctx.accounts.state.to_account_info()],
        &ctx.accounts.magic_context,
        &ctx.accounts.magic_program,
    )?;
    Ok(())
}

Undelegation

撤销委托

Returns PDA ownership to your program while committing final state.
rust
#[commit]  // Handles commit + undelegate
pub fn undelegate(ctx: Context<Undelegate>) -> Result<()> {
    Ok(())
}
将PDA所有权返还给你的程序,同时提交最终状态。
rust
#[commit]  // 处理提交+撤销委托
pub fn undelegate(ctx: Context<Undelegate>) -> Result<()> {
    Ok(())
}

ER Validators (Devnet)

ER验证器(Devnet)

RegionValidator Identity
Asia
MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57
EU
MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e
US
MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd
TEE
FnE6VJT5QNZdedZPnCoLsARgBwoE6DeJNjBs2H1gySXA
Magic Router (auto-selects best):
https://devnet-router.magicblock.app
区域验证器身份
亚洲
MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57
欧洲
MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e
美国
MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd
TEE
FnE6VJT5QNZdedZPnCoLsARgBwoE6DeJNjBs2H1gySXA
Magic Router(自动选择最优节点):
https://devnet-router.magicblock.app

Critical Rules

重要规则

DO:

需要做:

  • Maintain separate connections for base layer and ER
  • Use
    skipPreflight: true
    for all ER transactions
  • Verify delegation status before sending to ER
  • Use
    AccountInfo
    for delegated accounts in Rust
  • Match PDA seeds exactly between Rust and TypeScript
  • 为基础层和ER分别维护独立连接
  • 所有ER交易使用
    skipPreflight: true
  • 发送交易至ER前验证委托状态
  • 在Rust中使用
    AccountInfo
    处理委托账户
  • Rust与TypeScript中的PDA种子完全匹配

DON'T:

不要做:

  • Send delegated account operations to base layer
  • Mix base layer and ER operations in single transaction
  • Assume account ownership without checking
  • Skip commitment verification before base layer reads
  • 将委托账户操作发送至基础层
  • 在单个交易中混合基础层与ER操作
  • 未检查就假设账户所有权
  • 在读取基础层数据前跳过提交验证

Products

产品

ProductDescription
Ephemeral Rollup (ER)High-performance, gasless transactions
Private ER (PER)Privacy-preserving computation with Intel TDX
VRFVerifiable random function for on-chain randomness
BOLT FrameworkECS architecture for fully on-chain games
Solana PluginsApp-specific extensions for enhanced capabilities
产品描述
Ephemeral Rollup (ER)高性能、免Gas交易
Private ER (PER)基于Intel TDX的隐私保护计算
VRF用于链上随机数的可验证随机函数
BOLT Framework用于全链游戏的ECS架构
Solana Plugins增强功能的应用专属扩展

Solana Plugins (New)

Solana插件(新增)

Solana Plugins are modular capabilities that can be added to your dApp to extend what's possible on Solana. Think of them as your custom toolkit: plug in what you need, when you need it.
Solana插件是可添加到dApp的模块化功能,用于扩展Solana的能力范围。可将其视为自定义工具包:按需接入所需功能。

Available Plugins

可用插件

PluginDescriptionUse Cases
Verifiable Randomness (VRF)Provably fair on-chain randomnessGames, lotteries, NFT drops
Real-Time Price FeedsUp-to-the-millisecond market dataDEXs, trading bots, DeFi
AI OraclesCall AI models directly from smart contractsDynamic NFTs, AI agents
插件描述适用场景
可验证随机数(VRF)可证明公平的链上随机数游戏、彩票、NFT发售
实时价格馈送毫秒级更新的市场数据DEX、交易机器人、DeFi
AI预言机从智能合约直接调用AI模型动态NFT、AI Agent

Using VRF Plugin

使用VRF插件

typescript
import { requestRandomness, getRandomnessResult } from "@magicblock-labs/vrf-sdk";

// Request randomness
const requestTx = await requestRandomness({
  payer: wallet.publicKey,
  seed: Buffer.from("my_game_seed"),
});

// Get result after confirmation
const result = await getRandomnessResult(requestId);
console.log("Random value:", result.randomness);
typescript
import { requestRandomness, getRandomnessResult } from "@magicblock-labs/vrf-sdk";

// 请求随机数
const requestTx = await requestRandomness({
  payer: wallet.publicKey,
  seed: Buffer.from("my_game_seed"),
});

// 确认后获取结果
const result = await getRandomnessResult(requestId);
console.log("随机值:", result.randomness);

Privacy with Intel TDX

基于Intel TDX的隐私保护

MagicBlock enables privacy in any Solana program state account through Ephemeral Rollups running in Trusted Execution Environments (TEE) on Intel TDX. This allows:
  • Private computation without exposing state
  • Verifiable execution guarantees
  • Selective disclosure of results
MagicBlock通过运行在Intel TDX可信执行环境(TEE)中的Ephemeral Rollups,为任意Solana程序状态账户提供隐私保护。支持:
  • 不暴露状态的隐私计算
  • 可验证的执行保证
  • 结果的选择性披露

Resources

资源

Skill Structure

技能结构

magicblock/
├── SKILL.md                          # This file
├── resources/
│   ├── api-reference.md              # Complete API reference
│   └── program-ids.md                # All program IDs and constants
├── examples/
│   ├── anchor-counter/README.md      # Basic counter with delegation
│   ├── delegation-flow/README.md     # Full delegation lifecycle
│   ├── vrf-randomness/README.md      # VRF integration
│   └── crank-automation/README.md    # Scheduled tasks
├── templates/
│   ├── program-template.rs           # Rust program starter
│   └── client-template.ts            # TypeScript client starter
└── docs/
    ├── advanced-patterns.md          # Complex patterns
    └── troubleshooting.md            # Common issues
magicblock/
├── SKILL.md                          # 本文档
├── resources/
│   ├── api-reference.md              # 完整API参考
│   └── program-ids.md                # 所有程序ID与常量
├── examples/
│   ├── anchor-counter/README.md      # 带委托功能的基础计数器
│   ├── delegation-flow/README.md     # 完整委托生命周期
│   ├── vrf-randomness/README.md      # VRF集成
│   └── crank-automation/README.md    # 定时任务
├── templates/
│   ├── program-template.rs           # Rust程序模板
│   └── client-template.ts            # TypeScript客户端模板
└── docs/
    ├── advanced-patterns.md          # 复杂模式
    └── troubleshooting.md            # 常见问题