How do I generate a random integer in Cadence?

Daniela
Daniela
  • Updated

In Cadence, you can generate a random integer using the built-in revertibleRandom function.

Here's an example of how to use it:

access(all) fun main(min: UInt64, max: UInt64): UInt64 {
// use the built-in `revertibleRandom()` function
let randomNumber: UInt64 = revertibleRandom()
return (randomNumber % (max + 1 - min)) + min
}

This function generates a random number between the min and max values you provide. The revertibleRandom function returns a pseudo-random number and is based on the Distributed Random Beacon.

However, it's important to note that users can always abort their own transactions if the result is not favorable. Therefore, the revertibleRandom function should be used safely in applications where the transaction results are not deliberately reverted after the random number is revealed.

For more information, you can refer to the Flow documentation on randomness and the Cadence by Example course on the Flow Academy.