Wanted to know the best way to generate random numbers on anchor. I heard about oracles and switchboard but also heard on candy machine v2.

What would be the most efficient way to generate a random number? If you can provide documentation would be very helpful!


New contributor
user18905 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1


Depends on what you need the random numbers for.

A little primer on blockchains is that they need to be deterministic and replayable, meaning we cannot achieve true randomness on-chain. For example, Imagine having two validators running your program and they both call the function to generate a random number. Which number will be picked? How can the transaction be replayed?

There are a few ways to achieve pseudo-randomness on-chain.

Safer ways to achieve this making it hard for attackers to exploit your program

  • In this case is for a lottery, I head switchboard is a good choice but also heard of candymachine v2? is it good?
    – mark
    Commented Jun 11 at 19:31
  • Candy machine uses a combination of the slot_hash - timestamp to select the next item to mint, see github.com/metaplex-foundation/metaplex-program-library/blob/…. Candy Machine is not a PRNG library
    – Jimii
    Commented Jun 12 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.