Stellar VRF is a Verifiable Random Function oracle for the Stellar/Soroban blockchain. It generates cryptographically provable random numbers using BLS12-381 cryptography and the drand distributed randomness beacon.
Any dApp can request on-chain randomness by calling the VRF smart contract. The oracle fulfills the request with a BLS proof that the contract verifies on-chain, so every result is publicly verifiable against the registered oracle and drand keys.
CAW6KECQMHRTX2GS3JVHWBMOB5JNNOHNOCE635RQS4SWJ72YF56EUPRX
The fastest way to integrate. Install the SDK and call the contract with a few lines of code. Requires Node.js ≥ 22.12.0 (@stellar/stellar-sdk v17). The example below signs with a server-side keypair; in a browser, sign with a wallet such as Freighter instead (see Option C).
Prefer Rust? The Rust SDK is read/verify only: it queries results and reproduces derivations, but cannot submit request().
npm install stellar-vrf-sdk @stellar/stellar-sdk
import { VrfClient, Networks } from "stellar-vrf-sdk";
import { Keypair } from "@stellar/stellar-sdk";
const client = new VrfClient({
contractId: "CAW6KECQMHRTX2GS3JVHWBMOB5JNNOHNOCE635RQS4SWJ72YF56EUPRX",
rpcUrl: "https://mainnet.sorobanrpc.com",
networkPassphrase: Networks.PUBLIC,
// Server-side only: load the key from your secret store / environment.
// Never hard-code it, and never put a secret key in a web page.
keypair: Keypair.fromSecret(process.env.VRF_REQUESTER_SECRET),
});
// Context binds the randomness to your specific use case
const context = new TextEncoder().encode("audit-round-42");
const requestId = await client.request(context);
console.log("Request ID:", requestId);
// The oracle typically fulfills within 10–30 seconds
const proof = await client.waitForFulfillment(requestId, 120_000);
console.log("Beta output:", Buffer.from(proof.betaOutput).toString("hex"));
// Derive a random number in an inclusive range [1, 1000]
const result = await client.deriveRandomInRange(requestId, 1n, 1000n);
console.log("Random number:", result);
You can also derive a number from the beta output without any contract call:
JavaScript / TypeScriptimport { deriveRangeFromBeta } from "stellar-vrf-sdk";
// No network call needed — same result as the contract's
// derive_random_in_range(requestId, 100) + 1
const beta = await client.getBeta(requestId); // 32 bytes
const roll = 1n + deriveRangeFromBeta(beta, requestId, 100n);
For fully on-chain integration, your Soroban contract can request randomness and receive the result via a callback. This is the most secure approach — everything happens on-chain.
Your contract calls request_with_callback() on the VRF contract. When the oracle fulfills the request, the VRF contract calls your on_vrf() function automatically.
Rust (Soroban)pub fn request_sample(env: Env, requester: Address, range_max: u64) -> u64 {
requester.require_auth();
let vrf_contract: Address = env.storage().instance()
.get(&ConsumerKey::VrfContract).unwrap();
let context = Bytes::from_slice(&env, &range_max.to_be_bytes());
let self_addr = env.current_contract_address();
// The VRF contract will call on_vrf() when randomness is ready
let sample_id: u64 = env.invoke_contract(
&vrf_contract,
&Symbol::new(&env, "request_with_callback"),
vec![&env,
context.into_val(&env),
self_addr.clone().into_val(&env),
self_addr.into_val(&env),
Symbol::new(&env, "on_vrf").into_val(&env),
],
);
// Track the pending request
env.storage().persistent()
.set(&ConsumerKey::PendingSample(sample_id), &range_max);
sample_id
}
⚠️ Important: The VRF contract is the caller of on_vrf(), not the user or the oracle. You must call vrf_contract.require_auth() to verify the caller.
Rust (Soroban)pub fn on_vrf(env: Env, sample_id: u64, beta_output: BytesN<32>, _alpha_seed: BytesN<32>) {
// CRITICAL: Only the trusted VRF contract may call this
let vrf_contract: Address = env.storage().instance()
.get(&ConsumerKey::VrfContract).unwrap();
vrf_contract.require_auth();
// Idempotency: reject duplicate callbacks
if env.storage().persistent().has(&ConsumerKey::SampleResult(sample_id)) {
return;
}
// Validate this is a request we initiated
let range_max: u64 = env.storage().persistent()
.get(&ConsumerKey::PendingSample(sample_id))
.unwrap_or_else(|| panic!("unknown sample_id"));
// Exactly uniform value in [0, range_max): the same function as the VRF
// contract's derive_random_in_range(sample_id, range_max). Do NOT use
// `raw % range_max` on beta bytes: that is biased for most ranges.
let sample = derive_in_range(&env, sample_id, &beta_output, range_max);
env.storage().persistent()
.set(&ConsumerKey::SampleResult(sample_id), &sample);
}
/// Byte-for-byte copy of the VRF contract's derive_random_in_range():
/// h = sha256("VREP_DERIVE_V2" ‖ 0x02 ‖ request_id ‖ max ‖ beta), split into two
/// 128-bit candidates; exact rejection sampling, no modulo bias, no loop.
fn derive_in_range(env: &Env, request_id: u64, beta: &BytesN<32>, max: u64) -> u64 {
if max == 1 {
return 0;
}
let mut input = Bytes::from_slice(env, b"VREP_DERIVE_V2");
input.push_back(0x02);
input.append(&Bytes::from_slice(env, &request_id.to_be_bytes()));
input.append(&Bytes::from_slice(env, &max.to_be_bytes()));
input.append(&Bytes::from_slice(env, &beta.to_array()));
let h = env.crypto().sha256(&input).to_array();
let m = max as u128;
let rem = 0u128.wrapping_sub(m) % m; // 2^128 mod max
for half in [&h[0..16], &h[16..32]] {
let mut buf = [0u8; 16];
buf.copy_from_slice(half);
let c = u128::from_be_bytes(buf);
if c <= u128::MAX - rem {
return (c % m) as u64; // exact: c is below the largest multiple of max
}
}
panic!("range derivation failed: both candidates rejected"); // p < 2^-128
}
This is the function from consumer-example/src/lib.rs; its test asserts the shared vectors used by the contract and both SDKs (e.g. request 7, beta 00..1f, max 6 → 4).
If you prefer not to use the SDK package, you can call the VRF contract directly using the Stellar SDK from a CDN and let the user's wallet sign. This is how the Playground works on Mainnet. Never ask users to paste a secret key into a web page: use a wallet such as Freighter, which keeps the key in the extension and shows the user what they are signing.
HTML<script src="https://cdn.jsdelivr.net/npm/@stellar/stellar-sdk@17.0.1/dist/stellar-sdk.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@stellar/freighter-api@6.0.1/build/index.min.js"></script>
<script type="module">
const { TransactionBuilder, Operation, nativeToScVal, rpc, Networks } = StellarSdk;
const freighter = window.freighterApi;
const CONTRACT = "CAW6KECQMHRTX2GS3JVHWBMOB5JNNOHNOCE635RQS4SWJ72YF56EUPRX";
const PASSPHRASE = Networks.PUBLIC;
const server = new rpc.Server("https://mainnet.sorobanrpc.com");
// 1. Ask the wallet for the user's address (opens a Freighter prompt).
const access = await freighter.requestAccess();
if (access.error) throw new Error(access.error.message);
const address = access.address;
// 2. Build and simulate the request() transaction.
const account = await server.getAccount(address);
const tx = new TransactionBuilder(account, { fee: "2000000", networkPassphrase: PASSPHRASE })
.addOperation(Operation.invokeContractFunction({
contract: CONTRACT,
function: "request",
args: [
nativeToScVal(new TextEncoder().encode("my-context"), { type: "bytes" }),
nativeToScVal(address, { type: "address" }),
],
})).setTimeout(120).build();
const sim = await server.simulateTransaction(tx);
if (rpc.Api.isSimulationError(sim)) throw new Error(sim.error);
const prepared = rpc.assembleTransaction(tx, sim).build();
// 3. The wallet signs; the secret key never touches this page.
const signed = await freighter.signTransaction(prepared.toXDR(),
{ networkPassphrase: PASSPHRASE, address });
if (signed.error) throw new Error(signed.error.message);
await server.sendTransaction(TransactionBuilder.fromXDR(signed.signedTxXdr, PASSPHRASE));
</script>
Connect a funded Stellar account below to submit a real VRF request and see the full flow in action.