How to turn a VRF seed into a number in a range
To get a number from min to max out of a VRF word, use min + word % (max - min + 1). A VRF word is 256 bits, so modulo bias is at most n / 2^256, which is about 1 in 10^75 for a 1-to-100 roll, and you do not need rejection sampling. Bias does matter when you cut the word into 8- or 16-bit pieces: rolling 0 to 9,999 from 16-bit slices makes 5,536 of the outcomes 17% more likely than the rest. For several values, hash the seed with an index. Chainlink's own coordinator builds numWords that way, so asking for more words adds cost but no extra randomness. Below are a tested library, the bias counted over every input, and gas and price figures measured on Base.
The library
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// Turns one VRF seed into numbers in a range.
library RandomRange {
/// Value `i` drawn from `seed`. Chainlink's VRFCoordinatorV2_5 builds its `numWords` this way.
function word(uint256 seed, uint256 i) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(seed, i)));
}
/// A number from `min` to `max`, both included, from value `i` of `seed`.
/// Plain modulo of a 256-bit word: no outcome is more likely than another by more than 1 in 2^200
/// for any range below 2^56.
function between(uint256 seed, uint256 i, uint256 min, uint256 max) internal pure returns (uint256) {
require(min <= max, "empty range");
if (min == 0 && max == type(uint256).max) return word(seed, i);
return min + word(seed, i) % (max - min + 1);
}
/// An exactly uniform number from 0 to n - 1: words below 2^256 mod n are thrown away.
/// For a range below 2^56 the loop runs again less than once in 2^200 draws.
function uniform(uint256 seed, uint256 i, uint256 n) internal pure returns (uint256) {
require(n > 0, "empty range");
uint256 threshold;
unchecked {
threshold = (0 - n) % n; // 2^256 mod n
}
uint256 w = word(seed, i);
for (uint256 attempt = 1; w < threshold; ++attempt) {
w = uint256(keccak256(abi.encode(seed, i, attempt)));
}
return w % n;
}
}In a callback, give each decision its own index:
function _fulfillRandomSeed(bytes32 reqHash, uint256 seed) internal override {
uint256 damage = RandomRange.between(seed, 0, 10, 20); // 10 to 20
bool critical = RandomRange.between(seed, 1, 1, 100) <= 5; // 5%
uint256 lootIndex = RandomRange.between(seed, 2, 0, lootTable.length - 1);
// ...
}The full range 0 to type(uint256).max returns the word as it is, because max - min + 1 would overflow.
How large modulo bias is
x % n is biased when the number of possible x values is not a multiple of n. The first 2^b mod n outcomes then each get one more input than the others. The table gives that count and how much more likely those outcomes are, for each width of x. It is computed exactly, and the 8- and 16-bit rows are also counted over every input in the tests below.
Width of x | Range n | Outcomes with one extra input | How much more likely they are |
|---|---|---|---|
| 8 bits (a byte) | 6 | 4 (43 of 256 inputs each, the other two 42) | 2.4% |
| 8 bits | 100 | 56 (3 of 256 inputs each, the other 44 get 2) | 50% |
| 16 bits | 100 | 36 (656 of 65,536, the other 64 get 655) | 0.15% |
| 16 bits | 10,000 | 5,536 (7 of 65,536, the other 4,464 get 6) | 16.7% |
| 32 bits | 10,000 | 7,296 | 0.0002% |
| 64 bits | 10,000 | 1,616 | 5 × 10^-14 % |
| 256 bits (a VRF word) | 6 | 4 | 5 × 10^-75 % |
| 256 bits | 100 | 36 | 9 × 10^-74 % |
| 256 bits | 10,000 | 9,936 | 9 × 10^-72 % |
With a full VRF word, the bias is far below anything a player could measure or exploit: telling a d100 from a fair one would take more rolls than there are atoms in the universe. Pyth's guide to transforming Entropy results maps into a range with plain modulo and notes that the distortion is negligible for small and medium ranges. Audit contests still receive modulo-bias reports on VRF raffles, such as Immunefi report 49626 ("Modulo bias in winner selection in raffle", rated Insight), which flags rng[0] % totalTickets. Before you add code to fix it, check the width.
Where bias does show up: slicing a seed
A common gas saving is to cut one 256-bit seed into sixteen 16-bit pieces and take one roll from each, uint16(seed >> (16 * i)) % n. We measured that at 414 gas per extra roll, against 729 for a fresh keccak256(abi.encode(seed, i)). That saves 315 gas, about $0.000003 on Base at 0.006 gwei.
The bias is what you pay for those 315 gas. A loot table that rolls 0 to 9,999 and drops a rare item below 50 should drop it 0.50% of the time. From 16-bit slices, all 50 of those outcomes are among the 5,536 favoured ones, so the item drops 350 times in 65,536, which is 0.534%, or 6.8% more rare items than the table says. The same table with a hashed 256-bit roll matches the design. Use a slice only when the range divides 2^16 exactly (2, 4, 8, … 65,536) or when 0.15% for a d100 does not matter to you. Otherwise hash.
numWords or one seed?
Chainlink's coordinator does not run the VRF once per word. It runs it once and expands the output (VRFCoordinatorV2_5.sol in @chainlink/contracts 1.5.0, fulfillRandomWords):
randomWords = new uint256[](numWords);
for (uint256 i = 0; i < numWords; ++i) {
randomWords[i] = uint256(keccak256(abi.encode(randomness, i)));
}RandomRange.word(seed, i) is the same expression, and a test below checks that they match. Ten words from the coordinator and ten values you hash yourself from word 0 are equally unpredictable, because both are fixed by the same proof. Each of them is a hash of one VRF output.
What changes is the cost. On Base at block 65,456,161 (2026-12-03, gas price 0.006 gwei), with a 100,000 callback gas limit, this is how each quote changed when we asked for more words:
Change in calculateRequestPriceNative(100000, numWords) | 1 → 2 words | 1 → 10 words |
|---|---|---|
Chainlink VRF v2.5 wrapper 0xb0407dbe851f8318bd31404A49e658143C982F23 | +3,480,087,696 wei | +31,320,789,264 wei |
Randoo 0xC66eB2e7EE91145875000Ad46B55600000000001 | 0 | 0 |
Chainlink's wrapper adds 3,480,087,696 wei per extra word (its getConfig() lists 435 gas per word, and the quote adds a premium on top), which is about $0.000006 at the ETH price of that block. Randoo prices any numWords from 1 to 10 the same. The per-word fee is small. Storing what is delivered is not: each word you keep is a storage write in the callback (see the next section). On Randoo the other two interfaces deliver one seed: rawFulfillRandomSeed(bytes32, uint256) on the Ronin VRF interface and rawFulfillRandomness(uint256, bytes32) on the D20DAO interface. With D20DAO's interface you can also ask the coordinator for a range: requestMappedRandomness with a NumberRange, DiceRoll or ChooseMany spec, and getMappedResult(requestId) returns numbers that D20DAO's RandomnessMapping library has already mapped with rejection sampling.
Request one word, or one seed, per decision your game makes at one moment. Expand it in the contract, and send a new request only for a decision made later. See several VRF requests at once for that case.
Exactly uniform: rejection sampling, and the off-by-one
When a value has to be exactly uniform, for example for an auditor's checklist or when x is narrow, throw away the inputs that cause the bias and draw again. Two thresholds both work. Keep x >= 2^b mod n (what uniform() above, D20DAO's RandomnessMapping and OpenBSD's arc4random_uniform do), or keep x < 2^b - (2^b mod n).
The second threshold is often written with the type's maximum, limit = max - max % n, and then checked with <= where < belongs. Counted over every byte with n = 6, that version keeps 253 inputs: 0 gets 43 and the other outcomes 42 each, so the "fix" is still biased. The x >= 256 % 6 version keeps 252 inputs, 42 for each outcome. Both counts are tests below. A Zealynx audit of a pixel lottery rated a related bug High: both branches of the rejection check took the same modulo, so the correction did nothing.
With a 256-bit word, uniform() draws again less than once in 2^200 calls for any range under 2^56, and it cost 5,784 gas in an external call against 6,061 for between(). The rejection check costs nothing you can measure, so use whichever reads better to your reviewers.
One value per decision
Taking two numbers from the same word ties them together. With die = w % 6 + 1 and heads = w % 2 == 1, the coin comes up heads exactly when the die is even, in 1,000 of 1,000 seeds in the test below. The same holds for any pair of ranges where one divides the other: a d10 from w % 10 is the last digit of a d100 from w % 100. Give each decision its own index (between(seed, 0, …), between(seed, 1, …)). In the test, a die and a coin from indexes 0 and 1 agreed in 476 of 1,000 seeds, about half, as two independent draws should.
The same applies when you shuffle or pick several winners: each step of a Fisher-Yates shuffle takes keccak256(abi.encode(seed, i)) % (i + 1), as in the 52-card shuffle and the raffle's extra prizes.
Store the seed, not the words
The seed fixes every value you derive from it, so store the seed and compute value i when you need it. In Foundry, storing ten delivered words in an array cost 230,197 gas more than storing the one seed, about 23,000 gas for each new storage slot. On a VRF callback that gas counts against your callbackGasLimit, and you pay for the limit you reserve (see How to set a VRF callback gas limit). Recomputing a value later costs about 730 gas.
Tests we ran
RandomRange.sol compiles with Solidity 0.8.24 and 0.8.30. With forge 1.10.0 (optimizer on, 200 runs) and forge-std, these 13 tests pass:
- Bias, counted over every input: a byte
% 6gives 43, 43, 43, 43, 42, 42. Auint16 % 100gives 656 for 0 to 35 and 655 for 36 to 99.(0 - n) % nreturns 2^256 mod n: 0, 4, 36, 9,936 and 16 for n = 2, 6, 100, 10,000 and 52. - Rejection on a byte with n = 6: keeping
x >= 256 % 6gives 42 inputs per outcome, and thex <= max - max % nversion gives 43 for 0 and 42 for the rest. - One word for a die and a coin: heads exactly when the die is even, in 1,000 of 1,000 seeds. Indexes 0 and 1: 476 of 1,000.
betweenstays within 1 to 6 over 200 seeds, returns 5 for the range 5 to 5, and does not overflow on the full range.between(seed, i, 0, type(uint256).max)equals Chainlink'suint256(keccak256(abi.encode(randomness, i))).uniform(s, 0, 100)equalsbetween(s, 0, 0, 99)for 200 seeds. An empty range reverts in both.- Gas: 729 per extra hashed roll and 414 per extra sliced roll;
uniform5,784 andbetween6,061 per external call; ten stored words cost 230,197 more than one stored seed.
Try it on a testnet
Roll a free seed on Base Sepolia in the playground without a wallet, and check it on /verify. To build on it, take the consumer from the quickstart, add RandomRange.sol and call RandomRange.between(seed, i, min, max) in the callback. For a weighted table, see Loot box with VRF. If you are deciding whether a game needs a VRF at all, see Commit-reveal or VRF?
Sources (read 2026-12-03): VRFCoordinatorV2_5.sol and VRFV2PlusWrapper.sol in @chainlink/contracts 1.5.0 from npm; Pyth's "Transform Entropy results" (docs.pyth.network/entropy/transform-entropy-results); D20DAO's RandomnessMapping.sol (d20-sdk at fc4b546); Immunefi report 49626 (reports.immunefi.com); Zealynx finding F-2025-0004 (zealynx.io).
Updated 2026-12-03.