Search code examples
smartcontractsscrypto

How can we generate random values in Scrypto?


How can we generate random numbers in Scrypto if floating point libraries are not allowed be used? I want to be able to generate unique IDs for NFTs.


Solution

  • There are 2 ways to solve this:

    1. Self managed - if the data structure is a Vec, we can use vec.len() + 1 as the generated ID, making things more trivial.
    2. Generated Uuid - Scrypto provides Runtime::generate_uuid which is a generated number format in Uuid which should guarantee uniqueness

    We can also generate values given a max range:

    fn get_random(end: usize) -> usize {
        let num = Runtime::generate_uuid();
        (num % end as u128) as usize
    }
    
    // prints number between 0 - 5
    info!("{}", get_random(5));