Skip to main content

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.

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)
Never use simple on-chain methods like Clock::get()?.unix_timestamp for randomness - they are predictable and can be exploited!

Two Approaches

This example includes two implementations:
The standard approach where the player account remains on the base layer:
programs/roll-dice/src/lib.rs

How It Works

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

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

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:
  1. VRF Integration: Secure, verifiable randomness generation
  2. Callback Pattern: Asynchronous request-response flow
  3. ER-Optimized VRF: Using the ephemeral oracle queue for low-latency randomness
  4. Delegation: Managing player accounts in ERs for instant rolls
  5. 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: The demo showcases the difference in latency between delegated and non-delegated approaches.

Frontend Integration

Here’s how to call the roll dice function from your frontend:

Security Considerations

Important:
  • Always use the VRF oracle for randomness in production
  • Never trust client-provided random numbers
  • Verify the VRF program identity in callbacks
  • The caller_seed adds entropy but doesn’t replace VRF security
  • Store critical game logic on-chain, not in the client

Next Steps