error[E0432]: unresolved import `rand`

Are you calling this function from a different function marked #[query]?

Yes. Maybe it has to do with the fact that i deploy locally?

It is not possible to call other canisters in queries (at least for now). There are composite queries in the works, which will allow you to call other canisters, but for now you shouldn’t write calls to other canisters in your queries

Okay, got it, thanks.

But how then can I get some randomness? The only potential solution I have found so far is to call the “raw_rand” method on the management canister (as described in my code snippet). Is there a better way?

Have you tried this way: Issue about generate random string Panicked at 'could not initialize thread_rng: getrandom: this target is not supported' - #8 by AdamS ?

3 Likes

Yes, does not help, because it still relies on calling another canister in queries. Thanks anyway.

1 Like

No, it relies on calling another canister in the initializer.

However, no matter what, you cannot get (unique) randomness, or anything else that would update state, in a query call. The closest you could get would be if you concatenated randomness with time() and hashed the result, but that wouldn’t be very secure. Perhaps if you described what you were trying to do with it, it’d be easier to provide a solution.

1 Like

Hi Adam

Thanks for your reply. I recently just figured a work-around, which is as simple as it gets: i just tagged the function to be an “update” call. And it worked immediately. Probably not a really good way, but i still feel more comfortable than using time and hashing.

basically for now i only need the randomness to derive uuids.

all works for the time being. thank you very much!

1 Like

We create an rng that is stored globally and hooked up to a custom randomness implementation for the rand crate. In our init and post_upgrade functions we set a timer with delay 0 that retrieves randomness with raw_rand and sets the global rng. This is working so far.

3 Likes