magicblock
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMagicBlock 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
核心流程
- Initialize - Create accounts on Solana base layer
- Delegate - Transfer account ownership to delegation program
- Execute - Run fast operations on Ephemeral Rollup
- Commit - Sync state back to base layer
- Undelegate - Return ownership to your program
- 初始化 - 在Solana基础层创建账户
- 委托 - 将账户所有权转移至委托程序
- 执行 - 在Ephemeral Rollup上运行快速操作
- 提交 - 将状态同步回基础层
- 撤销委托 - 将账户所有权返还给你的程序
Prerequisites
前置条件
bash
undefinedbash
undefinedRequired 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
undefinedcargo install --git https://github.com/coral-xyz/anchor anchor-cli
undefinedQuick 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)
| Region | Validator Identity |
|---|---|
| Asia | |
| EU | |
| US | |
| TEE | |
Magic Router (auto-selects best):
https://devnet-router.magicblock.app| 区域 | 验证器身份 |
|---|---|
| 亚洲 | |
| 欧洲 | |
| 美国 | |
| TEE | |
Magic Router(自动选择最优节点):
https://devnet-router.magicblock.appCritical Rules
重要规则
DO:
需要做:
- Maintain separate connections for base layer and ER
- Use for all ER transactions
skipPreflight: true - Verify delegation status before sending to ER
- Use for delegated accounts in Rust
AccountInfo - 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
产品
| Product | Description |
|---|---|
| Ephemeral Rollup (ER) | High-performance, gasless transactions |
| Private ER (PER) | Privacy-preserving computation with Intel TDX |
| VRF | Verifiable random function for on-chain randomness |
| BOLT Framework | ECS architecture for fully on-chain games |
| Solana Plugins | App-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
可用插件
| Plugin | Description | Use Cases |
|---|---|---|
| Verifiable Randomness (VRF) | Provably fair on-chain randomness | Games, lotteries, NFT drops |
| Real-Time Price Feeds | Up-to-the-millisecond market data | DEXs, trading bots, DeFi |
| AI Oracles | Call AI models directly from smart contracts | Dynamic 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
资源
- Documentation: https://docs.magicblock.gg
- GitHub: https://github.com/magicblock-labs
- Examples: https://github.com/magicblock-labs/magicblock-engine-examples
- Starter Kits: https://github.com/magicblock-labs/starter-kits
- BOLT Book: https://book.boltengine.gg
- Discord: Join for testnet access
- 文档: https://docs.magicblock.gg
- GitHub: https://github.com/magicblock-labs
- 示例: https://github.com/magicblock-labs/magicblock-engine-examples
- 入门套件: https://github.com/magicblock-labs/starter-kits
- BOLT手册: https://book.boltengine.gg
- Discord: 加入获取测试网权限
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 issuesmagicblock/
├── 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 # 常见问题