Random

The convention is to name the module alias after the file name it is defined in.

import Random "mo:base/Random";

On this page

Class Finite

Function blob
Function byte
Function coin
Function range
Function binomial
Function byteFrom
Function coinFrom
Function rangeFrom
Function binomialFrom

Randomness on the IC

The IC provides a source of randomness for use in canister smart contracts. For non-cryptographic use cases, it is relatively simple to use, but for cryptographic use case, some care is required, see the Official Base Library Reference and the Official Docs for more information.

To obtain random numbers you need a source of entropy. Entropy is represented as a 32 byte Blob value. You may provide your own entropy Blob as a seed for random numbers or request 'fresh' entropy from the IC. Requesting entropy from the IC can only be done from within a shared function.

After obtaining a blob of entropy, you may use the Finite class to instantiate an object with methods to 'draw' different forms of randomness, namely:

  • A random Nat8 value with byte
  • A random Bool value with coin
  • A random Nat value within a (possibly) large range with range
  • A random Nat8 value of the number of heads in a series of n coin flips with binomial

When your entropy is 'used up', the Finite class methods will return null.

Alternatively, you may use byteFrom, coinFrom, rangeFrom and binomialFrom to obtain a single random value from a given Blob seed.

Class Finite

class Finite(entropy : Blob)

Random.blob

func blob : shared () -> async Blob

Random.byte

func byte() : ?Nat8

Random.coin

func coin() : ?Bool

Random.range

func range(p : Nat8) : ?Nat

Random.binomial

func binomial(n : Nat8) : ?Nat8

Random.byteFrom

func byteFrom(seed : Blob) : Nat8

Random.coinFrom

func coinFrom(seed : Blob) : Bool

Random.rangeFrom

func rangeFrom(p : Nat8, seed : Blob) : Nat

Random.binomialFrom

func binomialFrom(n : Nat8, seed : Blob) : Nat8