Last active
June 2, 2022 17:40
-
-
Save mattlockyer/4821401b74cfef788642316d6279f4fc to your computer and use it in GitHub Desktop.
NEAR Random Number (u128)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.