Using Randomness in Workflows
The problem: Why randomness needs special handling
Workflows often need randomness for various purposes: selecting winners from a list, sampling, or adding jitter. However, in a decentralized network, naive use of random number generators creates a critical problem:
If each node generates different random values, they cannot reach consensus on the workflow's output.
For example, if your workflow selects a lottery winner using each node's local random generator, different nodes would select different winners, making it impossible to agree on a single result to write onchain.
The solution: Consensus-safe randomness
CRE provides randomness through the Math.random() function inside the CRE WASM runtime. The SDK's WASM plugin overrides Math.random() with a seeded pseudo-random generator managed by the CRE platform. This ensures all nodes generate the same sequence of random values, enabling consensus. The generator is seeded from a hash of the workflow execution ID, so in production each execution gets a different sequence, but anyone who knows the execution ID and your workflow code can recompute the same values. The output is verifiable (anyone can re-derive it), not secret or unpredictable.
Usage
// Math.random() returns a value in the range [0, 1)
const randomFloat = Math.random()
// Convert to an integer in a range [0, 100)
const randomInt = Math.floor(Math.random() * 100)
// Convert to a bigint in a range [0, max)
const max = 1000000000000000000n // 1 ETH in wei
const randomBigInt = BigInt(Math.floor(Number(max) * Math.random()))
Common use cases
- Selecting an item from a pool or list where the choice only needs to be agreed upon by all nodes
- Sampling and load distribution
- Adding jitter or randomized ordering
- Tests and simulations
Do not use Math.random() for private keys, secrets, tokens, or signature nonces. See Secure Randomness in Confidential Workflows.
Working with bigint random values
For Solidity uint256 types, you often need random bigint values:
// Generate a random number in the range [0, max)
const max = 1000000000000000000n // 1 ETH in wei
const randomAmount = BigInt(Math.floor(Number(max) * Math.random()))
// randomAmount is a random value between 0 and 1 ETH
Because Math.random() returns a JavaScript number, be careful not to exceed Number.MAX_SAFE_INTEGER when scaling. For ranges larger than Number.MAX_SAFE_INTEGER, scale the float by a safe integer first, then combine with additional random draws, or use a deterministic multi-precision approach. For most workflow use cases (sampling, selection, prize amounts), the safe-integer range is sufficient.
Complete example: Random lottery
Here's a complete example that demonstrates using DON mode randomness to select a lottery winner and generate a prize amount:
import { CronCapability, handler, Runner, type Runtime, type CronPayload } from "@chainlink/cre-sdk"
type Config = {
schedule: string
}
type MyResult = {
winnerIndex: number
winner: string
randomBigInt: string
}
const onCronTrigger = (runtime: Runtime<Config>, payload: CronPayload): MyResult => {
runtime.log("Running random lottery")
// Define participants
const participants = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
runtime.log(`Participants in lottery: ${participants.join(", ")}`)
// Select a random winner (index in range [0, 5))
const winnerIndex = Math.floor(Math.random() * participants.length)
const winner = participants[winnerIndex]
runtime.log(`Selected winner: ${winner} (index ${winnerIndex})`)
// Generate a random prize amount up to 1,000,000 wei
const maxPrize = 1000000n
const randomPrize = BigInt(Math.floor(Number(maxPrize) * Math.random()))
runtime.log(`Generated random prize: ${randomPrize.toString()}`)
// Return the results
const result: MyResult = {
winnerIndex,
winner,
randomBigInt: randomPrize.toString(),
}
runtime.log(`Random lottery complete! ${JSON.stringify(result)}`)
return result
}
const initWorkflow = (config: Config) => {
const cron = new CronCapability()
return [handler(cron.trigger({ schedule: config.schedule }), onCronTrigger)]
}
export async function main() {
const runner = await Runner.newRunner<Config>()
await runner.run(initWorkflow)
}
What this example demonstrates:
-
DON mode context: The randomness is called directly in the trigger callback (DON mode), ensuring all nodes in the network would select the same winner and prize amount.
-
Random selection: Uses
Math.floor(Math.random() * participants.length)to select a random index from the participant list. -
Random bigint for Solidity: Generates a
bigintvalue suitable for use with Solidityuint256types. -
Logging: Uses
runtime.log()for output in the WASM environment.
In production, each execution has its own execution ID and therefore its own seed, so repeated executions select different winners and prize amounts. Within a single execution, all nodes in the DON arrive at the same winner. In simulation, the execution ID can be fixed, so running the same workflow twice may return the same result—don't rely on simulation for fresh randomness.
Best practices
Do:
- Always use
Math.random()inside the CRE WASM runtime for randomness in your workflows - Use
runtime.log()instead ofconsole.logfor output in the WASM environment
Don't:
- Don't use Node.js or browser random APIs directly. Always use
Math.random()inside the CRE WASM runtime. - Don't use
Math.random()for private keys, secrets, or tokens. The values are predictable by design.
Mode-aware behavior
The randomness provided by Math.random() is mode-aware. The examples above demonstrate DON mode (the default execution mode for workflows). There is also a Node mode with different random behavior, used in advanced scenarios. Each mode provides a different type of randomness.
DON mode (default)
The examples above all use DON mode. In this mode:
- All nodes generate the same random sequence
- Enables consensus on random values
- This is the mode your main workflow callback runs in
Node mode
When using runtime.runInNodeMode(), you can access Node mode randomness:
- Each node generates different random values
- Useful for scenarios where per-node variability is accepted
Math.random()inside the Node mode function uses the node-mode seed- Not cryptographically secure. Do not use it for keys, secrets, or tokens
Example:
import { consensusMedianAggregation, type Runtime, type NodeRuntime } from "@chainlink/cre-sdk"
const result = runtime
.runInNodeMode((nodeRuntime: NodeRuntime<Config>): number => {
// Each node generates a different value
return Math.floor(Math.random() * 100)
}, consensusMedianAggregation<number>())()
.result()
Important: Mode isolation
Random generators are tied to the mode they are called in. Do not attempt to use a random value generated in one mode inside another mode in a way that affects consensus — it will cause a panic and crash your workflow.
FAQ
Is the randomness cryptographically secure?
No. Math.random() returns values from a seeded pseudo-random number generator. In DON mode the seed is derived from a hash of the execution ID, so every node produces the same sequence. That is what makes consensus possible, and it is also why the values are predictable by anyone who knows the execution ID and your code. Do not use it for key generation, signature nonces, tokens, or any security-sensitive purpose.
Is there a way to get cryptographically secure randomness in TypeScript?
Not currently. Regular workflows can't provide it, because consensus requires every node to compute the same value. Confidential Workflows run in a secure enclave, but the TypeScript SDK does not yet expose a supported source of cryptographic randomness there. See Secure Randomness in Confidential Workflows. If you need cryptographic randomness today, use the Go SDK.
Does Chainlink VRF replace this?
They solve different problems. Chainlink VRF delivers randomness with an onchain cryptographic proof, so consumers don't need to trust any single party. Use it when you need onchain-verifiable randomness.
What happens if I try to use randomness in the wrong mode?
The SDK will panic with the error: "random cannot be used outside the mode it was created in". This is intentional — it prevents subtle consensus bugs.
Can I use the same random generator across multiple calls?
Yes. Once you are inside the CRE runtime, you can call Math.random() multiple times within the same execution mode. Each call produces the next value in the deterministic sequence.