Loot box with VRF
An on-chain loot box is fair when the drop comes from a seed that nobody knows when the box is bought and nobody can re-roll afterwards. The contract below does that with Randoo: the player pays and requests a seed in one transaction, and in a later block the oracle's callback rolls three items from a weighted rarity table. It runs unchanged on Ronin, Base and Robinhood with the coordinator 0xC66eB2e7EE91145875000Ad46B55600000000001, and it is tested, including the case where the callback fails.
Why not blockhash or prevrandao
A roll computed in the same transaction as the purchase can be undone. A player who calls open() from their own contract reads the item and reverts unless it is legendary, and pays only gas for each try. blockhash and prevrandao are also known to whoever builds the block, on Robinhood prevrandao is constant, and on Ronin and Base it is an Ethereum value that was public a minute or more before the block (Is block.prevrandao random?).
With a VRF request the purchase and the roll are separate transactions. open() only records the request and the player. The seed arrives in a later block from the oracle, so the player's transaction has nothing to read and nothing to revert. The seed is bound to the request block's hash, the request ID, your contract's address and the oracle's key hash, and a VRF proof admits one output per input, so the oracle cannot choose a different seed either. The coordinator checks the proof before it calls your contract, and a late fulfillment gives the same seed as a prompt one (timing).
The contract
Put the two files from the quickstart at src/RandooConsumerRonin.sol and src/interfaces/IRoninVRFCoordinatorForConsumers.sol, then add this one. Deploy it with 0xC66eB2e7EE91145875000Ad46B55600000000001 as the constructor argument.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {RandooConsumerRonin} from "./RandooConsumerRonin.sol";
import {IRoninVRFCoordinatorForConsumers} from "./interfaces/IRoninVRFCoordinatorForConsumers.sol";
interface IRandooSeeds {
function seedOf(bytes32 reqHash) external view returns (uint256 seed, bool fulfilled, bool callbackOk);
}
contract LootBox is RandooConsumerRonin {
enum Rarity {
Common,
Rare,
Epic,
Legendary
}
uint256 public constant ITEMS_PER_BOX = 3;
uint256 public constant CALLBACK_GAS = 150_000;
mapping(bytes32 => address) public playerOf;
mapping(bytes32 => bool) public opened;
mapping(address => mapping(Rarity => uint256)) public owned;
event BoxRequested(bytes32 indexed reqHash, address indexed player);
event BoxOpened(bytes32 indexed reqHash, address indexed player, Rarity[ITEMS_PER_BOX] drops);
constructor(address coordinator) RandooConsumerRonin(coordinator) {}
/// The player sends at least estimateRequestRandomFee(CALLBACK_GAS, gasPrice).
/// What the fulfillment does not use is refunded to the player.
function open() external payable returns (bytes32 reqHash) {
uint256 gasPrice = _declaredGasPrice();
uint256 fee = IRoninVRFCoordinatorForConsumers(vrfCoordinator).estimateRequestRandomFee(CALLBACK_GAS, gasPrice);
require(msg.value >= fee, "fee");
reqHash = _requestRandomness(msg.value, CALLBACK_GAS, gasPrice, msg.sender);
playerOf[reqHash] = msg.sender;
emit BoxRequested(reqHash, msg.sender);
}
/// Finishes a box whose callback failed, from the seed the coordinator stored.
function settle(bytes32 reqHash) external {
(uint256 seed, bool fulfilled,) = IRandooSeeds(vrfCoordinator).seedOf(reqHash);
require(fulfilled, "pending");
_open(reqHash, seed);
}
/// 70% common, 24% rare, 5.5% epic, 0.5% legendary.
function rarityOf(uint256 roll) public pure returns (Rarity) {
if (roll < 7_000) return Rarity.Common;
if (roll < 9_400) return Rarity.Rare;
if (roll < 9_950) return Rarity.Epic;
return Rarity.Legendary;
}
function _fulfillRandomSeed(bytes32 reqHash, uint256 seed) internal override {
_open(reqHash, seed);
}
function _open(bytes32 reqHash, uint256 seed) private {
address player = playerOf[reqHash];
require(player != address(0) && !opened[reqHash], "opened");
opened[reqHash] = true;
Rarity[ITEMS_PER_BOX] memory drops;
for (uint256 i; i < ITEMS_PER_BOX; ++i) {
uint256 roll = uint256(keccak256(abi.encode(seed, i))) % 10_000;
drops[i] = rarityOf(roll);
++owned[player][drops[i]];
}
emit BoxOpened(reqHash, player, drops);
}
/// Ronin and Saigon: 23 gwei. Base and Robinhood: the transaction's gas price.
function _declaredGasPrice() private view returns (uint256) {
if (block.chainid == 2020 || block.chainid == 202601) return 23 gwei;
return tx.gasprice;
}
}- One request per box. Each item gets its own roll,
keccak256(abi.encode(seed, i)) % 10_000, from the box's one seed. A fourth item adds callback gas, not a second fee. - Weights are cumulative thresholds out of 10,000. Change the numbers in
rarityOfand keep the last branch as the catch-all. Reducing a 256-bit seed modulo 10,000 skews each outcome by at most 10,000 / 2²⁵⁶, which is below 10⁻⁷². - Keep the table fixed while a box is pending. Here the weights are constants. If yours live in storage and an admin can change them, a change between a request and its fulfillment changes that box's odds. Store the table version with the request and roll against that version.
- The gas price to declare is 23 gwei on Ronin and Saigon and the transaction's gas price on Base and Robinhood. Fees and failures explains why.
- The player is the refund address.
open()forwards everything the player sent, and what the fulfillment does not use goes back to them, so no ETH or RON piles up in the contract. settlecovers a failed callback. If the callback reverts or runs out of gas, the request still counts as fulfilled and the coordinator stores the seed (callbacks). Anyone can then callsettle(reqHash), which readsseedOf(reqHash)and opens the box from that seed. Theopenedflag stops a box from being opened twice.- In a real game
ownedbecomes an ERC-1155 or ERC-721 mint. A mint costs more gas than a counter, so measure the callback again and raiseCALLBACK_GASto match (the limit is 50,000 to 2,500,000). To reveal a whole NFT collection after its sale instead of rolling per box, see NFT reveal with VRF.
Callback gas
We measured the callback in Foundry over 500 seeds, each for a new player whose counters were still empty, which is the most expensive case. It used 77,411 to 121,375 gas compiled with Solidity 0.8.38, via-IR and 200 optimizer runs, and 80,770 to 124,751 gas compiled with 0.8.30 without the optimizer. CALLBACK_GAS = 150_000 leaves about 20% headroom over the worst case. Most of the cost is storage writes from zero, about 22,100 gas each: the opened flag and one counter per rarity the player did not own before. How to set a VRF callback gas limit has the test that measures this for your own contract.
What a box costs
The player pays one request per box, whatever the number of items. estimateRequestRandomFee(150000, gasPrice) on each mainnet on 2026-11-16:
| Network | Block | Declared gas price | Prepaid by the player | Service fee in that |
|---|---|---|---|---|
| Ronin Mainnet | 63,672,037 | 23 gwei | 0.1501 RON (≈ $0.0056) | 0.1337 RON ($0.005) |
| Base | 58,112,462 | 0.006 gwei | 0.00000598 ETH (≈ $0.011) | 0.0000011 ETH ($0.002) |
| Robinhood | 115,580,792 | 0.020 gwei | 0.0000357 ETH (≈ $0.065) | 0.0000193 ETH ($0.035) |
The rest of the prepayment is gas for the callback and the fulfillment at the declared price with the coordinator's buffer, plus the L1 data fee on Base and Robinhood. The coordinator bills the gas the fulfillment actually used and refunds the rest to the player, so a box costs the service fee plus that gas. Dollar amounts convert at the coordinator's own price feed, which sets each service fee from the list price on Pricing.
Let players check their drop
BoxOpened carries the request hash. Link the player to /verify?q= followed by that hash: /verify finds the request on its network, re-derives the seed in the browser and checks the proof. With the seed, anyone can recompute the three rolls off chain and look them up in rarityOf:
import { encodeAbiParameters, keccak256 } from "viem";
const roll = (seed: bigint, i: bigint) =>
BigInt(keccak256(encodeAbiParameters([{ type: "uint256" }, { type: "uint256" }], [seed, i]))) % 10_000n;
const rolls = [0n, 1n, 2n].map((i) => roll(seed, i));For seed 12345 this gives 9237, 5214 and 9455, the same values the contract computes: rare, common, epic.
Tests we ran
The contract compiles with Solidity 0.8.30 and 0.8.38. Against the mock coordinator from the integration playbook, extended with seedOf and a fulfillment that starves the callback of gas, these pass:
- A box is requested, fulfilled, and the player owns three items.
open()with one wei less than the quote reverts withfee.- On chain ID 2020 (Ronin) the contract declares 23 gwei even when the transaction's gas price is zero.
- Only the coordinator can call
rawFulfillRandomSeed. - After a callback that ran out of gas,
settleopens the box once and a secondsettlereverts.settleon a pending request reverts withpending, and on a box the callback already opened withopened. rarityOfreturns the right rarity on both sides of every threshold.- 100,000 rolls land at 69.9% common, 24.1% rare, 5.4% epic and 0.5% legendary.
Try it on a testnet
Roll a free seed on Base Sepolia in the playground without a wallet and check it on /verify. Then deploy LootBox there with the quickstart's forge create command, with src/LootBox.sol:LootBox in place of the template, and call open() with at least the quoted fee.
Updated 2026-11-25.