-
-
Save mattlockyer/4821401b74cfef788642316d6279f4fc to your computer and use it in GitHub Desktop.
| // anywhere in your contract | |
| fn random_u128() -> u128 { | |
| let random_seed = env::random_seed(); // len 32 | |
| // using first 16 bytes (doesn't affect randomness) | |
| as_u128(random_seed.get(..16).unwrap()) | |
| } | |
| fn as_u128(arr: &[u8]) -> u128 { | |
| ((arr[0] as u128) << 0) + | |
| ((arr[1] as u128) << 8) + | |
| ((arr[2] as u128) << 16) + | |
| ((arr[3] as u128) << 24) + | |
| ((arr[4] as u128) << 32) + | |
| ((arr[5] as u128) << 40) + | |
| ((arr[6] as u128) << 48) + | |
| ((arr[7] as u128) << 56) + | |
| ((arr[8] as u128) << 64) + | |
| ((arr[9] as u128) << 72) + | |
| ((arr[10] as u128) << 80) + | |
| ((arr[11] as u128) << 88) + | |
| ((arr[12] as u128) << 96) + | |
| ((arr[13] as u128) << 104) + | |
| ((arr[14] as u128) << 112) + | |
| ((arr[15] as u128) << 120) | |
| } |
my man!
😆
Hey Matt, I am trying to use this in my contract but I get an error.
panicked at 'called Option::unwrap()on aNonevalue'
Any pointers on how to fix this?
Thanks
Are you sure it has to do with slicing the random seed value?
According to the docs it should still return a vec of u8
https://docs.rs/near-sdk/4.0.0-pre.4/near_sdk/env/fn.random_seed.html
I am not sure, but I have tried to isolate it and it seems to be the thing that fails. I am only learning rust so could totally be a simple error.
try not slicing it and logging the output, or using only 1 value from the vector.
Might be something wrong with your contract setup or the way you're running it e.g. perhaps env::random_seed isn't available in simulation tests or something?
I don't think it's available or has no real values in Rust unit tests.
Ok cool I am testing it with unit tests right now so that is probably the issue.
my man!