4

I've been trying to use most common

let mut rng = rand::thread_rng();
let winner_pos = rng.gen_range(0..10);

way to get a random number and use it in one of the contract's messages. But it throws a bunch of errors like:

error[E0277]: the size for values of type `u128` cannot be known at compilation time
   |
26 |         bids: ink_storage::Mapping<AccountId, Balance>,
   |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time

which are pretty misleading.

What is an alternative way to generate a random number then?

1
  • 1
    Also a note on this, you can't use libraries like rand since they typically get entropy from the operating system, which is not accessible from the context of a smart contract running on a blockchain.
    – HCastano
    Commented Jun 13, 2022 at 19:39

2 Answers 2

6

You can call self.env.random() to get the random seed associated with the block. However, any commitments using this must be implemented in previous blocks.

For example, if you're contract offered betting on the outcome of a dice roll, you would need to ask the bettors to bet at block n. The outcome of the bet is then calculated at block n+2 using self.env.random() to generate the dice roll outcome. The value of self.env.random() at block n+2 can be used because it was unknown at block n.

If you're trying to generate a random number between a min and a max, you can use something like this. In this example, the user account is passed to self.env.random() to create additional randomness.

2

I think ink_env, no longer provides support for random: https://docs.rs/ink_env/4.3.0/ink_env/#functions

What should be used for the moment?

2
  • 1
    there is article from Astar where we can generate random number in range here
    – go11li
    Commented Sep 14, 2023 at 2:36
  • thank you @Ganesh11 this is exactly what I was looking for. Weird that this isn't included in the official documents
    – munificent
    Commented Sep 14, 2023 at 6:28

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.