# NFT reveal with VRF

A fair NFT reveal fixes the order of the metadata before minting starts, closes minting, and only then draws one random offset that maps every token to its metadata file. The contract below does that with one Randoo request for the whole collection: anyone can start the reveal once the sale is over, and the oracle's callback sets the offset in a later block. It runs unchanged on Ronin, Base and Robinhood with the coordinator `0xC66eB2e7EE91145875000Ad46B55600000000001`, its callback fits in the coordinator's minimum of 50,000 gas, and it is tested, including the case where the callback fails.

## How reveals get gamed

Three things have to be true for a reveal to be fair, and each one has a known way to break:

- **The team cannot pick who gets what.** If the metadata order is decided after minting, the team can put the rare pieces on token IDs it holds. The fix is a provenance hash: a hash of every metadata file in slot order, stored in the contract before the first mint. After the reveal anyone can rehash the files and compare.
- **Nobody can mint after the outcome is known.** If minting is still open when the offset becomes public, a buyer reads it and mints when the next token ID maps to a rare slot. Anyone can compute the seed from the oracle's fulfillment transaction while it waits to be mined, so minting has to be closed before the request is sent, not just before the callback. The contract below refuses `reveal()` until the sale is over and refuses `mint()` after it.
- **The random number cannot be steered.** A starting index taken from `blockhash`, `block.timestamp` or the last minter's address can be chosen by whoever builds the block or sends the last transaction. On Robinhood `prevrandao` is constant, and on Ronin and Base anyone can read it on Ethereum before the block is built ([Is block.prevrandao random?](/docs/prevrandao)). A VRF seed is bound to the request block's hash, the request ID, your contract and the oracle's key hash, and its proof admits one output per input. The coordinator checks the proof before it calls your contract.

## The contract

Put the two files from the [quickstart](/docs/quickstart) at `src/RandooConsumerRonin.sol` and `src/interfaces/IRoninVRFCoordinatorForConsumers.sol`, install OpenZeppelin Contracts 5 (`forge install OpenZeppelin/openzeppelin-contracts`, remapped as `@openzeppelin/contracts/`), then add this one. Deploy it with `0xC66eB2e7EE91145875000Ad46B55600000000001`, the provenance hash, the time minting ends, the metadata base URI and the placeholder URI.

```solidity src/RevealedCollection.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
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 RevealedCollection is ERC721, RandooConsumerRonin {
    uint256 public constant MAX_SUPPLY = 10_000;
    uint256 public constant CALLBACK_GAS = 50_000;

    /// keccak256 of the MAX_SUPPLY metadata file hashes, in slot order, published before minting.
    bytes32 public immutable provenance;
    uint256 public immutable mintEnd;
    string private baseURI;
    string private hiddenURI;

    uint256 public totalMinted;
    bytes32 public revealRequest;
    // One storage slot: the callback writes it once.
    uint128 public offset;
    bool public revealed;

    event RevealRequested(bytes32 indexed reqHash);
    event Revealed(bytes32 indexed reqHash, uint256 offset);

    constructor(
        address coordinator,
        bytes32 provenance_,
        uint256 mintEnd_,
        string memory baseURI_,
        string memory hiddenURI_
    ) ERC721("Revealed", "RVL") RandooConsumerRonin(coordinator) {
        provenance = provenance_;
        mintEnd = mintEnd_;
        baseURI = baseURI_;
        hiddenURI = hiddenURI_;
    }

    function mint() external returns (uint256 tokenId) {
        require(block.timestamp < mintEnd && totalMinted < MAX_SUPPLY, "closed");
        tokenId = totalMinted++;
        _mint(msg.sender, tokenId);
    }

    /// Anyone can start the reveal once minting is over, sending at least
    /// estimateRequestRandomFee(CALLBACK_GAS, gasPrice). The unused part goes back to the caller.
    function reveal() external payable returns (bytes32 reqHash) {
        require(totalMinted == MAX_SUPPLY || block.timestamp >= mintEnd, "minting");
        require(revealRequest == bytes32(0), "requested");
        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);
        revealRequest = reqHash;
        emit RevealRequested(reqHash);
    }

    /// Finishes the reveal if the callback failed, from the seed the coordinator stored.
    function settle() external {
        (uint256 seed, bool fulfilled,) = IRandooSeeds(vrfCoordinator).seedOf(revealRequest);
        require(fulfilled, "pending");
        _reveal(revealRequest, seed);
    }

    /// The metadata file a token shows after the reveal: slots rotate by the random offset.
    function metadataIdOf(uint256 tokenId) public view returns (uint256) {
        require(revealed, "hidden");
        return (tokenId + offset) % MAX_SUPPLY;
    }

    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        _requireOwned(tokenId);
        if (!revealed) return hiddenURI;
        return string.concat(baseURI, Strings.toString(metadataIdOf(tokenId)), ".json");
    }

    function _fulfillRandomSeed(bytes32 reqHash, uint256 seed) internal override {
        _reveal(reqHash, seed);
    }

    function _reveal(bytes32 reqHash, uint256 seed) private {
        require(reqHash == revealRequest && !revealed, "revealed");
        offset = uint128(seed % MAX_SUPPLY);
        revealed = true;
        emit Revealed(reqHash, offset);
    }

    /// 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 for the collection.** The seed picks one offset, and token `t` shows metadata file `(t + offset) % MAX_SUPPLY`. That is a rotation, so no two tokens share a file, and each token is equally likely to land on any file. Requesting a seed per token would cost one service fee per token for no gain in fairness.
- **Minting has to be over before anyone can call `reveal()`:** sold out, or past `mintEnd`. After `mintEnd`, `mint()` reverts, so nobody can mint once the seed is public. If the collection does not sell out, the offset still runs over all `MAX_SUPPLY` slots and the unminted slots are never shown.
- **Anyone can reveal.** No owner key is needed, so a team that disappears cannot hold the reveal back. The caller pays the request and is the refund address, so what the fulfillment does not use goes back to them.
- **It reveals once.** `revealRequest` blocks a second request, and `revealed` blocks a second offset. There is no function to change the base URI, the provenance hash or the offset.
- **`settle` covers 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](/docs/gas#callbacks)). Anyone can then call `settle()`, which reads `seedOf(revealRequest)` and sets the offset from that seed.
- **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](/docs/gas#which-gas-price-to-declare) explains why.
- **Add your sale.** `mint()` here is free and has no per-wallet limit, so add your price and allowlist. If your metadata must stay private until the reveal, keep the provenance hash in the constructor and let the owner set `baseURI` once after `Revealed`: holders then check the uploaded files against the hash.

## Commit the metadata before the sale

The provenance hash is the keccak256 of every metadata file's keccak256, in slot order. Hash the file bytes exactly as you will publish them, and point each file's `image` at a content-addressed URI (an IPFS CID), so the hash also freezes the image. Pass the result to the constructor and publish it with the contract address before the first mint.

```ts Compute the provenance hash with viem
import { readFileSync } from "node:fs";
import { concat, keccak256 } from "viem";

const SUPPLY = 10_000;
const fileHashes = Array.from({ length: SUPPLY }, (_, i) => keccak256(readFileSync(`metadata/${i}.json`)));
const provenance = keccak256(concat(fileHashes));
```

Publish the list of file hashes too, so a holder can check one token without downloading the whole collection.

## Callback gas

The callback reads three storage slots and writes one, so its cost does not grow with the collection size. We searched for the smallest callback gas limit at which the coordinator's call still succeeds, from cold storage, for 200 seeds. The worst case was 28,434 gas compiled with Solidity 0.8.38, via-IR and 200 optimizer runs, and 30,077 gas with 0.8.30 without the optimizer. `CALLBACK_GAS = 50_000` is the coordinator's minimum, so it cannot go lower, and the worst case uses 61% of it. Keep `offset` and `revealed` next to each other: they share one storage slot, and two separate slots would add another 22,100 gas write.

## What a reveal costs

The whole collection costs one request. `estimateRequestRandomFee(50000, gasPrice)` on each mainnet on 2026-11-18:

| Network | Block | Declared gas price | Prepaid by the caller | Service fee in that |
| --- | --- | --- | --- | --- |
| Ronin Mainnet | 63,758,505 | 23 gwei | 0.1448 RON (≈ $0.0055) | 0.1309 RON ($0.005) |
| Base | 58,977,129 | 0.006 gwei | 0.00000523 ETH (≈ $0.0095) | 0.0000011 ETH ($0.002) |
| Robinhood | 117,220,391 | 0.020 gwei | 0.0000330 ETH (≈ $0.060) | 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 caller. Dollar amounts convert at the coordinator's own price feed, which sets each service fee from the list price on [Pricing](/pricing).

## Let holders check the reveal

A holder needs three checks, and each one uses public data:

1. **The seed.** `RevealRequested` and `Revealed` carry the request hash. Open `/verify?q=` followed by that hash: [/verify](/verify) finds the request on its network, re-derives the seed in the browser and checks the proof.
2. **The offset.** `offset` must equal the seed modulo 10,000, and token `t` must show file `(t + offset) % 10000`.
3. **The file.** The file's keccak256 must match its entry in the published hash list, and the hash of that list must match `provenance()` on the contract.

For seed 123,456,789 the offset is 6,789, so token 2 shows `6791.json` and token 9,999 shows `6788.json`.

## Rotation or full shuffle

A rotation keeps the team's slot order as a ring: tokens 41 and 42 show neighboring files. Each token is still equally likely to get any file, so no buyer can aim for a rare piece, but a collection whose files are sorted by rarity would hand out rares in runs. Shuffle the files before you compute the provenance hash, or derive a full permutation from the seed. D20DAO's reveal module does the latter with D20DAO's Shuffle mapping for collections of 1 to 64 tokens (D20DAO blog, 2026-10-18). A contract built on D20DAO's `D20VRFConsumer` runs on Randoo with `0xC66eB2e7EE91145875000Ad46B55600000000001` as its coordinator ([Migrate from D20DAO](/docs/d20dao)).

## Tests we ran

The contract compiles with Solidity 0.8.30 and 0.8.38. Against the mock coordinator from the [integration playbook](/docs/integrate), extended with `seedOf` and a fulfillment with a chosen gas limit, these pass:

- Before the reveal every token shows the placeholder URI. After the callback, `offset` is the seed modulo 10,000 and `tokenURI(2)` is the base URI plus `(2 + offset) % 10000` and `.json`.
- With offset 9,999, token 0 shows file 9,999 and token 1 wraps to file 0.
- Across all 10,000 token IDs, no two get the same file.
- `reveal()` while minting is open reverts with `minting`, `mint()` after `mintEnd` reverts with `closed`, and a second `reveal()` reverts with `requested`.
- `reveal()` with one wei less than the quote reverts with `fee`.
- 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 starved of gas, `settle` sets the offset once and a second `settle` reverts. `settle` on a pending request reverts with `pending`, and after a successful callback with `revealed`.
- `tokenURI` of an unminted token reverts.

## Try it on a testnet

Roll a free seed on Base Sepolia in the [playground](/playground?network=base-sepolia) without a wallet and check it on [/verify](/verify). Then deploy `RevealedCollection` there with the [quickstart's](/docs/quickstart) `forge create` command, with `src/RevealedCollection.sol:RevealedCollection` in place of the template and the five constructor arguments, mint a token, wait for `mintEnd` and call `reveal()` with at least the quoted fee. For a weighted roll per item instead of one reveal, see [Loot box with VRF](/docs/loot-box); for one winner drawn from weighted tickets, see [Raffle with VRF](/docs/raffle).

_Updated 2026-11-25._
