Sign in

Randomness on chain

Suggest an edit

Smart contracts can't generate random numbers on their own. Every value a contract can read is known to whoever proposes the block, so a number that nobody can choose has to come from outside the chain together with a proof. Chainlink VRF provides one, and it arrives in a separate transaction some blocks after the request.

Whoever proposes the block knows every value in it

Every node must execute every transaction and arrive at the same result, so a contract has no native source of randomness. If it called some rand() function and each node returned a different value, no two nodes would agree on the chain state, as the determinism lesson explained.

The standard workaround in beginner tutorials is to derive the number from values that already exist on chain: the block timestamp, the block hash, the previous block's randao value, the sender's address, transaction hashes. These are the same for everyone reading the chain, so consensus is preserved. They are also all chosen or seen by the validator proposing the block.

On-chain lottery seed: block.timestamp, block.prevrandao, and tx ordering, all proposer-controlledA lottery contract seeds a keccak256 hash with block.timestamp and block.prevrandao, and three boxes explain that timestamp, prevrandao, and transaction ordering are all chosen or seen by the block proposer. A four-step attack box shows a validator simulating the lottery locally, publishing the block only if it wins, and rerolling by skipping the block or changing transactions or the timestamp otherwise. Why on-chain "randomness" is manipulable A lottery contract picks a winner using block.timestamp as the seed: uint256 winner = uint256(keccak256(abi.encodePacked( block.timestamp, block.prevrandao )) % participants.length; The problem: every input is controlled or visible to the block proposer. block.timestamp Proposer picks the timestamp within a wide window block.prevrandao Proposer sees its value before committing the block tx ordering Proposer decides which transactions go in, in what order The attack 1. A malicious validator simulates the lottery locally before publishing. 2. If the result picks them (or their colluding wallet), they publish the block. 3. If not, they reroll: skip the block, retry with different transactions or timestamp. 4. The chain has no way to tell what was "rolled away."

A validator with a financial interest in the outcome simulates the draw before publishing its block and drops the block if it does not win. The cost of dropping a block is the lost block reward. If the lottery payout exceeds that, the attack is profitable, which is the case for pools worth more than a few ETH.

You cannot patch this by combining more sources. Any input the contract reads is an input the proposer can either control or see, and any deterministic function of public inputs produces an output the proposer can predict.

Commit-reveal lets the last participant reject the result

The next thing to try is to take the inputs from the participants and keep them hidden until nobody can react to them, as in the commit-reveal task. Each participant first submits the hash of a secret number. After all the hashes are in, each participant reveals the number, and the contract hashes the revealed numbers together. A participant cannot pick a number after seeing the others, and the proposer sees only hashes.

The scheme fails at the last reveal. The participant who reveals last already sees every other number, so they can compute the result before sending their own. If the result is bad for them, they do not send the reveal, and the draw either never finishes or has to be finished some other way. The last participant drops a reveal the way the proposer drops a block.

So the number has to come from a party that does not take part in the draw, and that party has to prove that it did not choose the number.

A VRF output comes with a proof that the oracle did not choose it

A Verifiable Random Function (VRF) 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:

  1. Someone supplies a seed, which can be anything: a block hash, a request ID, a sequence number.
  2. The oracle signs the seed with its private key using the VRF algorithm. This produces a random output and a proof.
  3. 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 output that the seed and the key determine, or its proof fails verification and the chain rejects the response. For the math, see the VRF protocol description on Chainlink's docs.

The number arrives in a second transaction

VRF cannot be a single function call. The proof must be generated off chain by the holder of the private key, so your contract submits a request in one transaction and receives the result in a second transaction some blocks later.

VRF request cycle: contract, VRF Coordinator, and VRF Service over two transactionsThree lanes show your contract, the on-chain VRF Coordinator, and the off-chain VRF Service exchanging messages over time. In transaction 1 your contract calls requestRandomWords() and the coordinator emits an event with a seed; the service signs the seed, waits N block confirmations, and submits the number and proof in transaction 2, which the coordinator verifies before calling fulfillRandomWords() so your contract stores the result. A VRF request takes two transactions, separated by an off-chain step Your contract VRF Coordinator (on chain) VRF Service (off chain) requestRandomWords() TX 1: user pays gas emit event with seed listens for event (off-chain log subscription) signs seed with private VRF key, produces (number, proof) waits N block confirmations submits (number, proof) TX 2: service pays gas verifies proof against public VRF key on-chain fulfillRandomWords() callback into your contract stores the result

You cannot use a random number in the same transaction that requests it, because the number does not exist yet. Your requestRandomWords call returns only a request ID. Anything the contract needs to do with the number (pick a winner, reveal an NFT, settle a bet) starts in the callback function and not in the original user transaction.

The service waits for a number of block confirmations before responding. A block at the tip of the chain can still be dropped in a reorg, as the consensus lesson described, and the request transaction with it, so the service reveals the number only after the request is several blocks deep. The number of confirmations is configurable per request, and the current minimum on Sepolia is 3. Higher values give you better protection against shallow reorgs, at the cost of waiting longer for the result.

In code

Your contract inherits from VRFConsumerBaseV2Plus, which provides the callback receiver and the coordinator reference. The request function builds a struct and calls the coordinator:

solidity
function requestRandomNumber() external returns (uint256 requestId) {
    requestId = s_vrfCoordinator.requestRandomWords(
        VRFV2PlusClient.RandomWordsRequest({
            keyHash: keyHash,
            subId: subscriptionId,
            requestConfirmations: requestConfirmations,
            callbackGasLimit: callbackGasLimit,
            numWords: numWords,
            extraArgs: VRFV2PlusClient._argsToBytes(
                VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
            )
        })
    );
}

subId is the subscription that pays for the request, a balance you fund in advance with LINK or native ETH. The consumer contract has to be registered on the subscription, or the coordinator rejects its requests. keyHash selects the gas lane, the off-chain VRF job that serves your request, and each lane has its own maximum gas price. requestConfirmations is the number of confirmations from the previous section, callbackGasLimit is the most gas the callback may use, and numWords is how many numbers you want back. The subscription docs cover the setup and the other fields, and the supported networks page lists the coordinator address and the valid key hashes for each chain.

The callback function is what your contract overrides to receive the result:

solidity
function fulfillRandomWords(
    uint256 requestId,
    uint256[] calldata randomWords
) internal override {
    uint256 result = randomWords[0];
    // ... store it, pick a winner, reveal an NFT, etc.
}

The function is internal and override. The base class exposes a public wrapper that checks the caller is the coordinator before invoking your override, so a result delivered by anything other than the coordinator is rejected before it reaches your code.

Each number is a uint256, distributed essentially uniformly across the full range of that type. To use it for a specific range, take the modulo:

solidity
uint256 diceRoll = (randomWords[0] % 20) + 1;       // 1 to 20
uint256 percent = randomWords[0] % 100;             // 0 to 99
address winner = participants[randomWords[0] % participants.length];

Modulo introduces a very slight bias when the modulus does not divide cleanly into the range of uint256. For a 20-sided die, the bias is on the order of one part in 2^251.

What VRF costs

A VRF number takes two transactions and a wait of several blocks. Someone has to pay for both the request transaction and the response transaction, plus a premium that compensates the oracle service.

The trust moves to the oracle. It cannot choose the number, but it computes the number before anyone else sees it, and it can fail to deliver it. You rely on the holder of the VRF key having no stake in your draw.

The number is not secret. The fulfillment transaction publishes everything, so anyone watching the chain sees the number as soon as that transaction is mined. If your contract logic depends on keeping the number hidden until later, that's not something VRF gives you.

What the consumer contract has to get right

Fix everything the number decides before you request it. The seed is set in the request transaction, so from that moment the number is determined, even though the chain has not seen it yet. The list of participants and their stakes has to be final in the same transaction. If a raffle still accepts entries or withdrawals after the request, anyone who learns the number before the contract acts on it can enter or leave knowing the result. The Solana Pro course calls this the commit-execution split.

Keep the callback small. If your fulfillRandomWords runs out of gas (because it does too much work, or the limit you set is too low), the random number is delivered to the coordinator but never reaches your contract's storage. The subscription is still charged for the work. Store the result and any derived values in the callback, then handle complex logic in a separate user-triggered transaction that reads from storage.

Decide what happens if the number never arrives. The proof guarantees that a delivered number is correct, not that it is delivered. If the service stays silent or the callback fails, a contract that can only finish in the callback keeps the players' money locked, so it needs a way out after a timeout. Both ways out give the service the option the last participant had in commit-reveal, because the service computes the number before it delivers it. If the contract returns the deposits, a service that holds back a number cancels that draw. If the contract requests again, the new request has a new seed, so the service also gets a different number. Either way the draw is fair only while the holder of the VRF key has no stake in it.

Record which requests are fulfilled. A request submitted near the tip of the chain can be confirmed in one block ordering and then re-organized into a different one. The same VRF response would still be valid (the seed and proof are deterministic), but your contract might process it twice if it doesn't track which requests have already been fulfilled. Use a flag in the request record to mark fulfilled requests and reject double-delivery.

Read Chainlink's security page before you deploy a consumer.