-2

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.

2 Answers2

2

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));
  • 4
    Just to add to this, generating random number is a really complex task in a smart contract environment. `Uuid::generate()` creates a random number in a deterministic way and also someone with a node could run the code until they get the number they want and only then submit the transaction. I suggest looking into this: https://docs.chain.link/docs/chainlink-vrf/, which is a way to have random numbers on chain more securily – Clement Apr 12 '22 at 09:14
0

You can generate a pseudo random NFT id using the built-in NonFungibleId::random() method.

let new_nft_id: NonFungibleId = NonFungibleId::random();

Reference: https://radixdlt.github.io/radixdlt-scrypto/scrypto/resource/struct.NonFungibleId.html

Fred Liebenberg
  • 101
  • 1
  • 5
  • Note that the generated id is only pseudo random, which makes it sufficient to use if your goal is to generate a unique id for an NFT. It is however not suitable if you need true randomness e.g. for a gambling application. See https://stackoverflow.com/questions/71849722/is-runtimegenerate-uuid-safe-in-scrypto for more info. – Fred Liebenberg Aug 26 '22 at 09:07