Issue about generate random string Panicked at 'could not initialize thread_rng: getrandom: this target is not supported'

This will return the same numbers every time. What you can do instead is seed an RNG of your choice with raw_rand. Once created and stored in a static, this RNG can be used synchronously. For example:

thread_local! {
    static RNG: RefCell<Option<StdRng>> = RefCell::new(None);
}
#[init]
fn init() {
    ic_cdk::timer::set_timer(Duration::ZERO, || ic_cdk::spawn(async {
        let (seed,): ([u8; 32],) = ic_cdk::call(Principal::management_canister(), "raw_rand", ()).await.unwrap();
        RNG.with(|rng| *rng.borrow_mut() = Some(StdRng::from_seed(seed)));
    }));
}
fn custom_getrandom(buf: &mut [u8]) -> Result<(), getrandom::Error> {
    RNG.with(|rng| rng.borrow_mut().as_mut().unwrap().fill_bytes(buf));
    Ok(())
}
4 Likes