Randomness on chain
Suggest an editSolana programs can't generate random numbers on their own. Real randomness has to come from an external source with a cryptographic proof, which is what MagicBlock VRF provides, and it arrives in a second transaction, some slots after the request.
Why a blockchain can't roll dice
The Solana runtime is a deterministic state machine. Every validator must execute every transaction and arrive at the same result, otherwise consensus breaks. If a program called some rand() function and each validator returned a different value, no two validators would agree on the chain state.
The standard workaround in beginner tutorials is to derive "randomness" from values that already exist on chain: the Clock sysvar's unix timestamp, the current slot number, the SlotHashes sysvar, recent transaction hashes, the caller's pubkey. These are deterministic for everyone reading the chain, so consensus is preserved. They are also all set or seen by the slot leader producing the block.
A leader with a financial interest in the outcome simulates the draw before publishing the block and skips the block if the result goes against it. The cost of skipping a slot is the lost block reward. If the lottery payout exceeds that, the attack is profitable. For pools worth more than a few SOL, whoever is the leader for the slot of the draw can afford this, because skipping costs one block reward and the outcome is drawn again in the next slot.
Anything visible inside the block is visible to whoever is producing it, and the leader chooses what to publish. You cannot patch this by combining more sources. Any input the program reads is an input the leader can either control or see, and any deterministic function of public inputs produces an output the leader can predict.
The oracle cannot choose a VRF output
The Verifiable Random Function (VRF) protocol is a cryptographic construction that produces two things at once: a pseudorandom output, and a proof that the output was generated correctly from a specific seed using a specific private key.
The party generating randomness, the VRF oracle service, holds the private key. The public key is published on chain in advance. The protocol works like this:
- Someone supplies a seed, which can be anything: a slot number, a request ID, a sequence number.
- The oracle signs the seed with its private key using the VRF algorithm. This produces a random output and a proof.
- Anyone with the public key can verify, by examining the proof, that the output was generated from that seed using that key, and that the oracle had no freedom to choose the output.
The oracle cannot try multiple seeds, see the outputs, and publish only the one it likes, because the seed is committed to in the proof. The oracle cannot reuse a previously favorable output for a new seed, because the proof will not verify. Either it returns the cryptographically determined output, or its proof fails verification and the on-chain program rejects the response.
The number arrives in a second transaction
VRF cannot be a single instruction call. The proof must be generated off chain by an entity holding the private key, and that work cannot happen inside a normal program execution. The pattern is asynchronous: your program submits a request in one transaction, and receives the result in a second transaction some slots later.
You cannot use a random number in the same transaction that requests it, because the number does not exist yet. The request CPI completes by adding a pending request to the oracle's queue account, and the user's transaction returns successfully. Anything the program needs to do with the number (pick a winner, reveal an NFT, settle a bet) happens in the second transaction, inside the handler that the VRF program calls back (the callback), rather than in the original user transaction.
The split would be needed even if the number could be produced on the spot. A user who gets a random outcome inside their own transaction can simulate the transaction first and send it only when it wins. So the user's transaction only commits to the bet, and someone else, here the oracle, sends the transaction that brings the result. Solana PRO covers this pattern in the commit-execution split lesson.
Under normal load, fulfillment happens within a few slots, often within a second of the original request. The user pays for the request transaction in SOL. The oracle pays for the fulfillment transaction itself and charges a fee that gets debited from the requester at request time.
In code
Your program needs two instructions: one to make the request, and one to receive the callback. The request is a CPI into the MagicBlock VRF program, which adds the request, with a seed and the callback target, to the oracle's queue account. The callback handler is a normal instruction with one extra constraint: it can only be called by the MagicBlock VRF program.
When the VRF program delivers the number, it calls the callback through a CPI and signs for its identity PDA, which it derives from the seed identity and your program's ID. Only the VRF program can sign for that PDA, so the callback takes it as its first account, typed Signer, with an address constraint computed by scoped_vrf_identity from MagicBlock's ephemeral-vrf-sdk crate.
#[derive(Accounts)]
pub struct ReceiveRandomness<'info> {
#[account(address = ephemeral_vrf_sdk::consts::scoped_vrf_identity(&crate::ID))]
pub vrf_program_identity: Signer<'info>,
#[account(mut)]
pub lottery: Account<'info, Lottery>,
}
pub fn receive_randomness(ctx: Context<ReceiveRandomness>, randomness: [u8; 32]) -> Result<()> {
let lottery = &mut ctx.accounts.lottery;
let n = lottery.participants.len() as u64;
let winner_idx = u64::from_le_bytes(randomness[..8].try_into().unwrap()) % n;
lottery.winner = lottery.participants[winner_idx as usize];
Ok(())
}Anchor checks the signature and the address before the handler runs. A direct call can name the PDA but cannot carry its signature, so it reverts before reaching your code. Without such a check, anyone could call the handler with a number of their own choosing. The handler receives the number as 32 bytes and takes the first 8 bytes as a u64 modulo the number of participants.
What can go wrong
The number is public as soon as it is delivered. The fulfillment transaction publishes everything, and anyone watching the chain sees the result as soon as it lands. If your program logic depends on keeping the number hidden until later, that is not something VRF gives you, and you need a different protocol.
Entries have to close before the request. The oracle knows the number before the chain does. If the callback only stores the number and a later instruction picks the winner, as the next point recommends, everyone knows it before the winner is recorded. If participants can still join or withdraw after the request, whoever learns the number first can change the participant list so that the draw goes their way. The request instruction has to lock everything the number decides, here the participant list and the stakes, and keep it locked until the winner is recorded.
The callback can fail. If your receive_randomness handler runs out of compute units, panics on a checked-arithmetic overflow, or hits an Anchor constraint failure, the whole fulfillment transaction reverts, including the VRF program's part of it. The request stays in the queue until it expires and is removed, your program does not receive the randomness, and the fee you paid at request time is not refunded. Keep callbacks minimal: store the result and any cheap derived values, and save complex logic for a separate user-triggered instruction that reads from storage. The handler above can panic too: with no participants, % n divides by zero, so the request instruction has to reject an empty lottery.
The oracle may never answer. The proof makes a delivered number correct, but nothing makes the oracle deliver it, and a callback that reverts leaves the program in the same place. A lottery that can only finish in the callback then holds the pot forever, so it needs an exit: if no number has arrived by a deadline, participants take their stakes back. A second request is the other exit. Neither exit takes away the oracle's option to hold back a number it does not like: the refund cancels that draw and a second request repeats it, which is what the slot leader got by skipping a block. Solana PRO's write the exit task asks for the same guarantee: the players' stakes must come back even if the round is never settled.