I tried unsafeRandom and this custom smart-contract without success: https://github.com/justjoolz/PRNG/blob/master/cadence/contracts/PRNG.cdc
Asked
Active
Viewed 82 times
1
-
What issue did you have? – j00lz Feb 22 '23 at 08:19
-
The usage example mentioned in the link doesn't work for me, I created a test script that imports that smart-contract, maybe I'm doing something wrong since I'm new to Cadence. I expected to find something simpler to generate a random number – ziny Feb 22 '23 at 10:09
-
Random numbers on chain are not straight forward. Easy to get wrong hence unsafeRandom being Cadence's only offering. You can see how ChainMonsters used the PRNG contract here: https://flow-view-source.com/mainnet/account/0x93615d25d14fa337/contract/ChainmonstersFoundation Note that they are dual signing transactions with an Admin account to ensure transactions can't be reverted with a panic statement – j00lz Feb 24 '23 at 03:45
1 Answers
0
As mentioned by @j00lz, you can create a random between two integers (more specifically UInt256
types) by using the PRNG
contract found here.
Essentially, you create a Generator resource based on a seed (or block height + integer), and call functions on that generator.
Here is a helpful example of how to use it (try it out here):
import PRNG from 0x93615d25d14fa337
pub fun main(min: UInt256, max: UInt256): UInt256 {
// create the generator resource
let generator <- PRNG.createFrom(blockHeight: getCurrentBlock().height, uuid: 100)
// call the range function to give you an integer between min and max
let answer: UInt256 = generator.range(min, max)
// destroy the generator resource
destroy generator
// return your answer
return answer
}

Jacob Tucker
- 132
- 7