Documentation Index
Fetch the complete documentation index at: https://mintlify.com/magicblock-labs/magicblock-engine-examples/llms.txt
Use this file to discover all available pages before exploring further.
Roll Dice
The Roll Dice example demonstrates how to integrate MagicBlock’s Verifiable Random Function (VRF) to generate provably fair random numbers within Ephemeral Rollups. This is essential for games, lotteries, and any application requiring unpredictable, tamper-proof randomness.Try the live demo at https://roll-dice-demo.vercel.app
What is VRF?
A Verifiable Random Function (VRF) generates random numbers that are:- Unpredictable: Cannot be predicted before generation
- Verifiable: Can be proven to be random
- Tamper-proof: Cannot be manipulated by validators or users
- Deterministic: Given the same input, produces the same output (verifiable)
Two Approaches
This example includes two implementations:- Non-Delegated
- Delegated (Recommended)
The standard approach where the player account remains on the base layer:
programs/roll-dice/src/lib.rs
How It Works
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],
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)?;
#[vrf]
#[derive(Accounts)]
pub struct DoRollDiceDelegatedCtx<'info> {
#[account(mut)]
pub payer: Signer<'info>,
#[account(seeds = [PLAYER_SEED, payer.key().to_bytes().as_slice()], bump)]
pub player: Account<'info, Player>,
/// CHECK: The oracle queue
#[account(mut, address = ephemeral_vrf_sdk::consts::DEFAULT_EPHEMERAL_QUEUE)]
pub oracle_queue: AccountInfo<'info>,
}
pub fn callback_roll_dice_simple(
ctx: Context<CallbackRollDiceSimpleCtx>,
randomness: [u8; 32],
) -> Result<()> {
let player = &mut ctx.accounts.player;
let rnd_u8 = ephemeral_vrf_sdk::rnd::random_u8_with_range(&randomness, 1, 6);
msg!("Consuming random number: {:?}", rnd_u8);
player.rollnum = player.rollnum.saturating_add(1);
msg!("Roll number: {:?}", player.rollnum);
player.last_result = rnd_u8;
Ok()
}
#[derive(Accounts)]
pub struct CallbackRollDiceSimpleCtx<'info> {
/// This check ensures that the vrf_program_identity (which is a PDA) is a signer
/// enforcing the callback is executed by the VRF program through CPI
#[account(address = ephemeral_vrf_sdk::consts::VRF_PROGRAM_IDENTITY)]
pub vrf_program_identity: Signer<'info>,
#[account(mut)]
pub player: Account<'info, Player>,
}
Oracle Queues
Different oracle queues for different environments:Player Account Structure
programs/roll-dice-delegated/src/lib.rs
Random Number Utilities
The VRF SDK provides helper functions for common use cases:Delegated vs Non-Delegated
- Delegated (Advanced)
- Non-Delegated
Benefits:
- Ultra-low latency rolls in the ER
- Rapid successive rolls without base layer delays
- Can batch multiple rolls before committing
- Perfect for real-time gaming
Delegating the Player Account
For the delegated approach, delegate the player account to the ER:programs/roll-dice-delegated/src/lib.rs
Required Dependencies
Cargo.toml
What Makes This Advanced?
This example demonstrates several advanced concepts:- VRF Integration: Secure, verifiable randomness generation
- Callback Pattern: Asynchronous request-response flow
- ER-Optimized VRF: Using the ephemeral oracle queue for low-latency randomness
- Delegation: Managing player accounts in ERs for instant rolls
- Seed Management: Using client seeds for additional entropy
Use Cases
- Dice Games: Provably fair dice rolls (shown in this example)
- Loot Drops: Random item generation in games
- Lotteries: Fair winner selection
- Card Shuffling: Randomized deck ordering
- Procedural Generation: Random dungeon/world generation
- NFT Traits: Random trait assignment at mint
Live Demo
Experience the dice rolling in action:- Demo URL: https://roll-dice-demo.vercel.app
- Delegated Demo: https://roll-dice-demo.vercel.app/delegated
Frontend Integration
Here’s how to call the roll dice function from your frontend:Security Considerations
Next Steps
- Explore Session Keys to enable gasless dice rolls
- Learn about Magic Actions to trigger rewards on lucky rolls
- Check the full source code
- Try the live demo