Any Solana program can request and consume verifiable randomness onchain within seconds using the MagicBlock VRF SDK. By the end of this guide, you’ll have a working example that rolls a dice using verifiable randomness.
Process of Requesting
and Consuming
Onchain Randomness
1
Write your Solana program as you normally would, using Anchor, native Rust,
Bolt, C, or even assembly.
2
Add request and consume randomness instructions
Add CPI hooks that request and consume randomness via callback from a
verified oracle.
3
Deploy your Solana program using Anchor or Solana CLI.
4
Execute transactions for onchain randomness
Run your transactions to generate and consume randomness onchain.
Step 1: Write your program
Start with a simple dice program that includes aninitialize
instruction and a Player
struct to store the randomness result:
Step 2: Add request randomness
and consume randomness
instructions
Request Randomness
is the process of generating a randomhashId
with the relevant callback instruction for the verified oracles to be triggered.
Consume Randomness
is the process of using the verifiable randomness which is provided and triggered by verified oracle.
Anchor framework example:
- Add
ephemeral_vrf_sdk
with Anchor features to your program
vrf
, create_request_randomness_ix
, RequestRandomnessParams
, and SerializableAccountMeta
:
- Add instructions
roll_dice
to request randomness andcallback_roll_dice
to consume randomness, along with its context: